From 18ea13f629564a7f7915783444621a8e92bcec5b Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 22 Oct 2025 15:08:35 -0700 Subject: [PATCH 01/40] Pure auto-gen code --- .../azure-search-documents/azure/__init__.py | 7 +- .../azure/search/__init__.py | 7 +- .../azure/search/documents/__init__.py | 56 +- .../azure/search/documents/_api_versions.py | 17 - .../_search_index_client.py => _client.py} | 48 +- .../azure/search/documents/_configuration.py | 79 + .../documents/_generated/_configuration.py | 53 - .../documents/_generated/aio/__init__.py | 27 - .../_generated/aio/_configuration.py | 53 - .../aio/operations/_documents_operations.py | 1130 -- .../documents/_generated/models/__init__.py | 154 - .../_generated/models/_models_py3.py | 3098 ---- .../operations/_documents_operations.py | 1520 -- .../search/documents/_generated/py.typed | 1 - .../azure/search/documents/_headers_mixin.py | 21 - .../documents/_index_documents_batch.py | 145 - .../azure/search/documents/_paging.py | 182 - .../documents/{_generated => }/_patch.py | 0 .../azure/search/documents/_queries.py | 135 - .../azure/search/documents/_search_client.py | 746 - .../documents/_search_documents_error.py | 10 - .../_search_indexing_buffered_sender.py | 359 - .../_search_indexing_buffered_sender_base.py | 51 - .../azure/search/documents/_utils.py | 81 - .../{_generated => }/_utils/__init__.py | 4 +- .../search/documents/_utils/model_base.py | 1237 ++ .../{_generated => }/_utils/serialization.py | 6 +- .../azure/search/documents/_utils/utils.py | 57 + .../azure/search/documents/_validation.py | 66 + .../azure/search/documents/_version.py | 15 +- .../azure/search/documents/agent/__init__.py | 29 - .../search/documents/agent/_agent_client.py | 97 - .../agent/_generated/_configuration.py | 53 - .../agent/_generated/aio/__init__.py | 27 - .../agent/_generated/aio/_configuration.py | 53 - .../_knowledge_retrieval_operations.py | 193 - .../agent/_generated/models/__init__.py | 80 - ..._knowledge_agent_retrieval_client_enums.py | 26 - .../agent/_generated/models/_models_py3.py | 1112 -- .../_knowledge_retrieval_operations.py | 228 - .../documents/agent/_generated/py.typed | 1 - .../search/documents/agent/aio/__init__.py | 29 - .../agent/aio/_agent_client_async.py | 98 - .../search/documents/agent/models/__init__.py | 78 - .../azure/search/documents/aio/__init__.py | 51 +- .../_client.py} | 52 +- .../search/documents/aio/_configuration.py | 83 + .../aio/_index_documents_batch_async.py | 139 - .../azure/search/documents/aio/_paging.py | 164 - .../documents/{_generated => }/aio/_patch.py | 0 .../documents/aio/_search_client_async.py | 743 - .../_search_indexing_buffered_sender_async.py | 362 - .../azure/search/documents/aio/_timer.py | 20 - .../operations/__init__.py | 6 +- .../documents/aio/operations/_operations.py | 1382 ++ .../{_generated => }/aio/operations/_patch.py | 0 .../search/documents/indexes/__init__.py | 53 +- .../_search_service_client.py => _client.py} | 81 +- .../documents/indexes/_configuration.py | 72 + .../documents/indexes/_generated/__init__.py | 27 - .../indexes/_generated/_configuration.py | 48 - .../indexes/_generated/_utils/utils.py | 23 - .../indexes/_generated/aio/__init__.py | 27 - .../indexes/_generated/aio/_configuration.py | 48 - .../_generated/aio/operations/__init__.py | 39 - .../aio/operations/_aliases_operations.py | 611 - .../operations/_data_sources_operations.py | 592 - .../aio/operations/_indexers_operations.py | 1093 -- .../aio/operations/_indexes_operations.py | 849 - .../_knowledge_agents_operations.py | 583 - .../_knowledge_sources_operations.py | 583 - .../_search_service_client_operations.py | 195 - .../aio/operations/_skillsets_operations.py | 748 - .../operations/_synonym_maps_operations.py | 579 - .../indexes/_generated/models/__init__.py | 586 - .../indexes/_generated/models/_models_py3.py | 13171 ---------------- .../indexes/_generated/operations/__init__.py | 39 - .../operations/_aliases_operations.py | 755 - .../operations/_data_sources_operations.py | 749 - .../operations/_indexers_operations.py | 1394 -- .../operations/_indexes_operations.py | 1058 -- .../_knowledge_agents_operations.py | 727 - .../_knowledge_sources_operations.py | 727 - .../_search_service_client_operations.py | 237 - .../operations/_skillsets_operations.py | 940 -- .../operations/_synonym_maps_operations.py | 731 - .../documents/indexes/_generated/py.typed | 1 - .../{_generated/models => indexes}/_patch.py | 0 .../documents/indexes/_search_index_client.py | 847 - .../indexes/_search_indexer_client.py | 741 - .../azure/search/documents/indexes/_utils.py | 80 - .../{_generated => }/_utils/__init__.py | 4 +- .../documents/indexes/_utils/model_base.py | 1237 ++ .../{_generated => }/_utils/serialization.py | 6 +- .../search/documents/indexes/_utils/utils.py | 57 + .../search/documents/indexes/aio/__init__.py | 50 +- .../_client.py} | 82 +- .../documents/indexes/aio/_configuration.py | 74 + .../operations => indexes/aio}/_patch.py | 0 .../indexes/aio/_search_index_client.py | 841 - .../indexes/aio/_search_indexer_client.py | 691 - .../indexes/aio/operations/__init__.py | 40 + .../indexes/aio/operations/_operations.py | 5495 +++++++ .../aio/operations}/_patch.py | 0 .../documents/indexes/models/__init__.py | 468 +- .../search/documents/indexes/models/_edm.py | 19 - .../_enums.py} | 258 +- .../search/documents/indexes/models/_index.py | 908 -- .../documents/indexes/models/_models.py | 13026 +++++++++++++-- .../aio => indexes/models}/_patch.py | 0 .../documents/indexes/operations/__init__.py | 40 + .../indexes/operations/_operations.py | 6807 ++++++++ .../aio => indexes}/operations/_patch.py | 0 .../{_generated => knowledgebase}/__init__.py | 11 +- .../_client.py} | 53 +- .../documents/knowledgebase/_configuration.py | 72 + .../models => knowledgebase}/_patch.py | 0 .../_utils/__init__.py | 4 +- .../knowledgebase/_utils/model_base.py | 1237 ++ .../_utils/serialization.py | 6 +- .../documents/knowledgebase/_utils/utils.py | 57 + .../aio}/__init__.py | 8 +- .../aio/_client.py} | 52 +- .../knowledgebase/aio/_configuration.py | 74 + .../aio}/_patch.py | 0 .../aio/operations/__init__.py | 6 +- .../aio/operations/_operations.py | 248 + .../aio/operations}/_patch.py | 0 .../knowledgebase/models/__init__.py | 106 + .../documents/knowledgebase/models/_enums.py | 48 + .../documents/knowledgebase/models/_models.py | 1627 ++ .../aio => knowledgebase/models}/_patch.py | 0 .../operations/__init__.py | 6 +- .../knowledgebase/operations/_operations.py | 283 + .../operations/_patch.py | 0 .../azure/search/documents/models/__init__.py | 152 +- .../_enums.py} | 19 +- .../azure/search/documents/models/_models.py | 2184 +++ .../{indexes/_generated => }/models/_patch.py | 0 .../aio => }/operations/__init__.py | 6 +- .../documents/operations/_operations.py | 1826 +++ .../_generated => }/operations/_patch.py | 0 .../azure/search/documents/py.typed | 1 + .../azure-search-documents/samples/README.md | 73 - .../sample_analyze_text_async.py | 47 - .../sample_authentication_async.py | 91 - .../sample_autocomplete_async.py | 49 - .../sample_buffered_sender_async.py | 56 - .../sample_crud_operations_async.py | 73 - .../sample_data_source_operations_async.py | 81 - .../async_samples/sample_facet_query_async.py | 52 - .../sample_filter_query_async.py | 54 - .../sample_get_document_async.py | 48 - ...ample_index_alias_crud_operations_async.py | 111 - .../sample_index_client_send_request_async.py | 49 - .../sample_index_crud_operations_async.py | 127 - .../sample_indexers_operations_async.py | 132 - .../sample_query_session_async.py | 49 - ...sample_search_client_send_request_async.py | 49 - .../sample_semantic_search_async.py | 71 - .../sample_simple_query_async.py | 49 - .../async_samples/sample_suggestions_async.py | 50 - .../sample_synonym_map_operations_async.py | 80 - .../sample_vector_search_async.py | 203 - .../samples/files/hotel_small.json | 252 - .../samples/sample_analyze_text.py | 45 - .../samples/sample_authentication.py | 89 - .../samples/sample_autocomplete.py | 46 - .../samples/sample_buffered_sender.py | 51 - .../samples/sample_crud_operations.py | 67 - .../samples/sample_data_source_operations.py | 72 - .../samples/sample_facet_query.py | 49 - .../samples/sample_filter_query.py | 51 - .../samples/sample_get_document.py | 45 - .../sample_index_alias_crud_operations.py | 105 - .../sample_index_client_send_request.py | 47 - .../samples/sample_index_crud_operations.py | 116 - .../sample_indexer_datasource_skillset.py | 152 - .../samples/sample_indexers_operations.py | 123 - .../samples/sample_query_session.py | 47 - .../sample_search_client_send_request.py | 47 - .../samples/sample_semantic_search.py | 70 - .../samples/sample_simple_query.py | 46 - .../samples/sample_suggestions.py | 47 - .../samples/sample_synonym_map_operations.py | 89 - .../samples/sample_vector_search.py | 204 - .../samples/synonym_map.txt | 2 - .../async_tests/test_buffered_sender_async.py | 159 - .../async_tests/test_search_client_async.py | 30 - .../test_search_client_basic_live_async.py | 45 - ...earch_client_buffered_sender_live_async.py | 173 - ...search_client_index_document_live_async.py | 169 - .../test_search_client_search_live_async.py | 160 - ...st_search_index_client_alias_live_async.py | 111 - .../test_search_index_client_async.py | 114 - ...rch_index_client_data_source_live_async.py | 120 - .../test_search_index_client_live_async.py | 190 - ...search_index_client_skillset_live_async.py | 217 - ...rch_index_client_synonym_map_live_async.py | 147 - .../test_search_indexer_client_live_async.py | 154 - .../azure-search-documents/tests/conftest.py | 36 - .../tests/hotel_large.json | 1504 -- .../tests/hotel_schema.json | 288 - .../tests/hotel_small.json | 254 - .../tests/perfstress_tests/README.md | 47 - .../tests/perfstress_tests/__init__.py | 0 .../tests/perfstress_tests/autocomplete.py | 55 - .../perfstress_tests/search_documents.py | 56 - .../tests/perfstress_tests/suggest.py | 55 - .../tests/search_service_preparer.py | 158 - .../tests/test_buffered_sender.py | 154 - .../tests/test_index_documents_batch.py | 69 - .../tests/test_index_field_helpers.py | 90 - .../tests/test_models.py | 45 - .../tests/test_queries.py | 165 - .../tests/test_regex_flags.py | 102 - .../tests/test_search_client.py | 323 - .../tests/test_search_client_basic_live.py | 41 - ...test_search_client_buffered_sender_live.py | 168 - .../test_search_client_index_document_live.py | 167 - .../tests/test_search_client_search_live.py | 134 - .../tests/test_search_index_client.py | 130 - .../test_search_index_client_alias_live.py | 108 - ...st_search_index_client_data_source_live.py | 136 - .../tests/test_search_index_client_live.py | 185 - .../test_search_index_client_skillset_live.py | 252 - ...st_search_index_client_synonym_map_live.py | 145 - .../tests/test_search_indexer_client_live.py | 158 - .../tests/test_serialization.py | 108 - 229 files changed, 37008 insertions(+), 55064 deletions(-) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_api_versions.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/_search_index_client.py => _client.py} (68%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_paging.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_queries.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/_utils.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/_utils/__init__.py (52%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/_utils/serialization.py (99%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/_validation.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/_knowledge_retrieval_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_knowledge_agent_retrieval_client_enums.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_models_py3.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/_knowledge_retrieval_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/_generated/py.typed delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/aio/_agent_client_async.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/agent/models/__init__.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/aio/_search_index_client.py => aio/_client.py} (69%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/aio/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => aio}/operations/__init__.py (70%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated => }/aio/operations/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated/_search_service_client.py => _client.py} (61%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_agents_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_agents_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed rename sdk/search/azure-search-documents/azure/search/documents/{_generated/models => indexes}/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated => }/_utils/__init__.py (52%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated => }/_utils/serialization.py (99%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated/aio/_search_service_client.py => aio/_client.py} (62%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py rename sdk/search/azure-search-documents/azure/search/documents/{_generated/operations => indexes/aio}/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated => indexes/aio/operations}/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{_generated/models/_search_service_client_enums.py => models/_enums.py} (83%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated/aio => indexes/models}/_patch.py (100%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated/aio => indexes}/operations/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{_generated => knowledgebase}/__init__.py (65%) rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated/_knowledge_agent_retrieval_client.py => knowledgebase/_client.py} (65%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_configuration.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated/models => knowledgebase}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated => knowledgebase}/_utils/__init__.py (52%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/model_base.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated => knowledgebase}/_utils/serialization.py (99%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/utils.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated => knowledgebase/aio}/__init__.py (68%) rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated/aio/_knowledge_agent_retrieval_client.py => knowledgebase/aio/_client.py} (67%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_configuration.py rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated/operations => knowledgebase/aio}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated => knowledgebase}/aio/operations/__init__.py (70%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated => knowledgebase/aio/operations}/_patch.py (100%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated/aio => knowledgebase/models}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{agent/_generated => knowledgebase}/operations/__init__.py (70%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated/aio => knowledgebase}/operations/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{_generated/models/_search_index_client_enums.py => models/_enums.py} (96%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/models/_models.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated => }/models/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{_generated/aio => }/operations/__init__.py (70%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py rename sdk/search/azure-search-documents/azure/search/documents/{indexes/_generated => }/operations/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/samples/README.md delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py delete mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py delete mode 100644 sdk/search/azure-search-documents/samples/files/hotel_small.json delete mode 100644 sdk/search/azure-search-documents/samples/sample_analyze_text.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_authentication.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_autocomplete.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_buffered_sender.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_crud_operations.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_data_source_operations.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_facet_query.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_filter_query.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_get_document.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_index_client_send_request.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_index_crud_operations.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_indexers_operations.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_query_session.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_search_client_send_request.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_semantic_search.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_simple_query.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_suggestions.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py delete mode 100644 sdk/search/azure-search-documents/samples/sample_vector_search.py delete mode 100644 sdk/search/azure-search-documents/samples/synonym_map.txt delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py delete mode 100644 sdk/search/azure-search-documents/tests/conftest.py delete mode 100644 sdk/search/azure-search-documents/tests/hotel_large.json delete mode 100644 sdk/search/azure-search-documents/tests/hotel_schema.json delete mode 100644 sdk/search/azure-search-documents/tests/hotel_small.json delete mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/README.md delete mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/__init__.py delete mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py delete mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py delete mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py delete mode 100644 sdk/search/azure-search-documents/tests/search_service_preparer.py delete mode 100644 sdk/search/azure-search-documents/tests/test_buffered_sender.py delete mode 100644 sdk/search/azure-search-documents/tests/test_index_documents_batch.py delete mode 100644 sdk/search/azure-search-documents/tests/test_index_field_helpers.py delete mode 100644 sdk/search/azure-search-documents/tests/test_models.py delete mode 100644 sdk/search/azure-search-documents/tests/test_queries.py delete mode 100644 sdk/search/azure-search-documents/tests/test_regex_flags.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_client.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_client_basic_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_client_search_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py delete mode 100644 sdk/search/azure-search-documents/tests/test_serialization.py diff --git a/sdk/search/azure-search-documents/azure/__init__.py b/sdk/search/azure-search-documents/azure/__init__.py index 4c33a0853ef3..d55ccad1f573 100644 --- a/sdk/search/azure-search-documents/azure/__init__.py +++ b/sdk/search/azure-search-documents/azure/__init__.py @@ -1,6 +1 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint:disable=missing-docstring -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/__init__.py b/sdk/search/azure-search-documents/azure/search/__init__.py index 4c33a0853ef3..d55ccad1f573 100644 --- a/sdk/search/azure-search-documents/azure/search/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/__init__.py @@ -1,6 +1 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint:disable=missing-docstring -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/__init__.py index cdb1217ba956..63ab1b900961 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/__init__.py @@ -1,44 +1,32 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._index_documents_batch import IndexDocumentsBatch -from ._search_documents_error import RequestEntityTooLargeError -from ._search_client import SearchClient, SearchItemPaged -from ._search_indexing_buffered_sender import SearchIndexingBufferedSender -from ._api_versions import ApiVersion +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchClient # type: ignore from ._version import VERSION __version__ = VERSION +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk -__all__ = ( - "ApiVersion", - "IndexDocumentsBatch", +__all__ = [ "SearchClient", - "SearchItemPaged", - "SearchIndexingBufferedSender", - "RequestEntityTooLargeError", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py b/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py deleted file mode 100644 index 63bbb287e1c8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py +++ /dev/null @@ -1,17 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - V2020_06_30 = "2020-06-30" - V2023_11_01 = "2023-11-01" - V2024_07_01 = "2024-07-01" - V2025_08_01_PREVIEW = "2025-08-01-preview" - - -DEFAULT_VERSION = ApiVersion.V2025_08_01_PREVIEW diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/_client.py similarity index 68% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py rename to sdk/search/azure-search-documents/azure/search/documents/_client.py index 122aa5e41f78..c5b9b7226926 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_client.py @@ -1,42 +1,54 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import PipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import SearchIndexClientConfiguration +from ._configuration import SearchClientConfiguration from ._utils.serialization import Deserializer, Serializer from .operations import DocumentsOperations +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class SearchIndexClient: - """Client that can be used to query an index and upload, merge, or delete documents. + +class SearchClient: + """SearchClient. :ivar documents: DocumentsOperations operations :vartype documents: azure.search.documents.operations.DocumentsOperations - :param endpoint: The endpoint URL of the search service. Required. + :param endpoint: Service host. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential :param index_name: The name of the index. Required. :type index_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, index_name: str, **kwargs: Any + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], index_name: str, **kwargs: Any ) -> None: - _endpoint = "{endpoint}/indexes('{indexName}')" - self._config = SearchIndexClientConfiguration(endpoint=endpoint, index_name=index_name, **kwargs) + _endpoint = "{endpoint}" + self._config = SearchClientConfiguration( + endpoint=endpoint, credential=credential, index_name=index_name, **kwargs + ) _policies = kwargs.pop("policies", None) if _policies is None: @@ -57,19 +69,18 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.documents = DocumentsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -84,7 +95,6 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_configuration.py new file mode 100644 index 000000000000..f6f346ca1211 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_configuration.py @@ -0,0 +1,79 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class SearchClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], index_name: str, **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if index_name is None: + raise ValueError("Parameter 'index_name' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.index_name = index_name + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py deleted file mode 100644 index 5ebd4a3efbe9..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchIndexClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param index_name: The name of the index. Required. - :type index_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, index_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if index_name is None: - raise ValueError("Parameter 'index_name' must not be None.") - - self.endpoint = endpoint - self.index_name = index_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchindexclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py deleted file mode 100644 index b24a07c02d65..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_index_client import SearchIndexClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchIndexClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py deleted file mode 100644 index ed4c0a0a8a8d..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchIndexClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param index_name: The name of the index. Required. - :type index_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, index_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if index_name is None: - raise ValueError("Parameter 'index_name' must not be None.") - - self.endpoint = endpoint - self.index_name = index_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchindexclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py deleted file mode 100644 index 29df61ea153e..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_documents_operations.py +++ /dev/null @@ -1,1130 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._documents_operations import ( - build_autocomplete_get_request, - build_autocomplete_post_request, - build_count_request, - build_get_request, - build_index_request, - build_search_get_request, - build_search_post_request, - build_suggest_get_request, - build_suggest_post_request, -) -from .._configuration import SearchIndexClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class DocumentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`documents` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def count(self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any) -> int: - """Queries the number of documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Count-Documents - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: int or the result of cls(response) - :rtype: int - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[int] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_count_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("int", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def search_get( - self, - search_text: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - search_options: Optional[_models.SearchOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. Default value is None. - :type search_text: str - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param search_options: Parameter group. Default value is None. - :type search_options: ~azure.search.documents.models.SearchOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _include_total_result_count = None - _facets = None - _filter = None - _highlight_fields = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _query_type = None - _scoring_parameters = None - _scoring_profile = None - _search_fields = None - _search_mode = None - _scoring_statistics = None - _session_id = None - _select = None - _skip = None - _top = None - _x_ms_client_request_id = None - _semantic_configuration = None - _semantic_error_handling = None - _semantic_max_wait_in_milliseconds = None - _answers = None - _captions = None - _semantic_query = None - _query_rewrites = None - _debug = None - _query_language = None - _speller = None - _semantic_fields = None - if search_options is not None: - _answers = search_options.answers - _captions = search_options.captions - _debug = search_options.debug - _facets = search_options.facets - _filter = search_options.filter - _highlight_fields = search_options.highlight_fields - _highlight_post_tag = search_options.highlight_post_tag - _highlight_pre_tag = search_options.highlight_pre_tag - _include_total_result_count = search_options.include_total_result_count - _minimum_coverage = search_options.minimum_coverage - _order_by = search_options.order_by - _query_language = search_options.query_language - _query_rewrites = search_options.query_rewrites - _query_type = search_options.query_type - _scoring_parameters = search_options.scoring_parameters - _scoring_profile = search_options.scoring_profile - _scoring_statistics = search_options.scoring_statistics - _search_fields = search_options.search_fields - _search_mode = search_options.search_mode - _select = search_options.select - _semantic_configuration = search_options.semantic_configuration - _semantic_error_handling = search_options.semantic_error_handling - _semantic_fields = search_options.semantic_fields - _semantic_max_wait_in_milliseconds = search_options.semantic_max_wait_in_milliseconds - _semantic_query = search_options.semantic_query - _session_id = search_options.session_id - _skip = search_options.skip - _speller = search_options.speller - _top = search_options.top - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_search_get_request( - search_text=search_text, - include_total_result_count=_include_total_result_count, - facets=_facets, - filter=_filter, - highlight_fields=_highlight_fields, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - query_type=_query_type, - scoring_parameters=_scoring_parameters, - scoring_profile=_scoring_profile, - search_fields=_search_fields, - search_mode=_search_mode, - scoring_statistics=_scoring_statistics, - session_id=_session_id, - select=_select, - skip=_skip, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - semantic_configuration=_semantic_configuration, - semantic_error_handling=_semantic_error_handling, - semantic_max_wait_in_milliseconds=_semantic_max_wait_in_milliseconds, - answers=_answers, - captions=_captions, - semantic_query=_semantic_query, - query_rewrites=_query_rewrites, - debug=_debug, - query_language=_query_language, - speller=_speller, - semantic_fields=_semantic_fields, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def search_post( - self, - search_request: _models.SearchRequest, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: ~azure.search.documents.models.SearchRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def search_post( - self, - search_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def search_post( - self, - search_request: Union[_models.SearchRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Is either a SearchRequest type or - a IO[bytes] type. Required. - :type search_request: ~azure.search.documents.models.SearchRequest or IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(search_request, (IOBase, bytes)): - _content = search_request - else: - _json = self._serialize.body(search_request, "SearchRequest") - - _request = build_search_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get( - self, - key: str, - selected_fields: Optional[list[str]] = None, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> dict[str, Any]: - """Retrieves a document from the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/lookup-document - - :param key: The key of the document to retrieve. Required. - :type key: str - :param selected_fields: List of field names to retrieve for the document; Any field not - retrieved will be missing from the returned document. Default value is None. - :type selected_fields: list[str] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: dict mapping str to any or the result of cls(response) - :rtype: dict[str, any] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[dict[str, Any]] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - key=key, - selected_fields=selected_fields, - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("{object}", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def suggest_get( - self, - search_text: str, - suggester_name: str, - suggest_options: Optional[_models.SuggestOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param suggest_options: Parameter group. Default value is None. - :type suggest_options: ~azure.search.documents.models.SuggestOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _search_fields = None - _select = None - _top = None - _x_ms_client_request_id = None - if suggest_options is not None: - _filter = suggest_options.filter - _highlight_post_tag = suggest_options.highlight_post_tag - _highlight_pre_tag = suggest_options.highlight_pre_tag - _minimum_coverage = suggest_options.minimum_coverage - _order_by = suggest_options.order_by - _search_fields = suggest_options.search_fields - _select = suggest_options.select - _top = suggest_options.top - _use_fuzzy_matching = suggest_options.use_fuzzy_matching - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_suggest_get_request( - search_text=search_text, - suggester_name=suggester_name, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - search_fields=_search_fields, - select=_select, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def suggest_post( - self, - suggest_request: _models.SuggestRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def suggest_post( - self, - suggest_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def suggest_post( - self, - suggest_request: Union[_models.SuggestRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Is either a SuggestRequest type or a IO[bytes] - type. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(suggest_request, (IOBase, bytes)): - _content = suggest_request - else: - _json = self._serialize.body(suggest_request, "SuggestRequest") - - _request = build_suggest_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def index( - self, - batch: _models.IndexBatch, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexBatch - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def index( - self, - batch: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def index( - self, - batch: Union[_models.IndexBatch, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Is either a IndexBatch type or a IO[bytes] type. - Required. - :type batch: ~azure.search.documents.models.IndexBatch or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.IndexDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(batch, (IOBase, bytes)): - _content = batch - else: - _json = self._serialize.body(batch, "IndexBatch") - - _request = build_index_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 207]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("IndexDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def autocomplete_get( - self, - search_text: str, - suggester_name: str, - request_options: Optional[_models.RequestOptions] = None, - autocomplete_options: Optional[_models.AutocompleteOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param search_text: The incomplete term which should be auto-completed. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :param autocomplete_options: Parameter group. Default value is None. - :type autocomplete_options: ~azure.search.documents.models.AutocompleteOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - _autocomplete_mode = None - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _search_fields = None - _top = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - if autocomplete_options is not None: - _autocomplete_mode = autocomplete_options.autocomplete_mode - _filter = autocomplete_options.filter - _highlight_post_tag = autocomplete_options.highlight_post_tag - _highlight_pre_tag = autocomplete_options.highlight_pre_tag - _minimum_coverage = autocomplete_options.minimum_coverage - _search_fields = autocomplete_options.search_fields - _top = autocomplete_options.top - _use_fuzzy_matching = autocomplete_options.use_fuzzy_matching - - _request = build_autocomplete_get_request( - search_text=search_text, - suggester_name=suggester_name, - x_ms_client_request_id=_x_ms_client_request_id, - autocomplete_mode=_autocomplete_mode, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - search_fields=_search_fields, - top=_top, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def autocomplete_post( - self, - autocomplete_request: _models.AutocompleteRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def autocomplete_post( - self, - autocomplete_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def autocomplete_post( - self, - autocomplete_request: Union[_models.AutocompleteRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Is either a - AutocompleteRequest type or a IO[bytes] type. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(autocomplete_request, (IOBase, bytes)): - _content = autocomplete_request - else: - _json = self._serialize.body(autocomplete_request, "AutocompleteRequest") - - _request = build_autocomplete_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py deleted file mode 100644 index 061cb503b94a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/__init__.py +++ /dev/null @@ -1,154 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AutocompleteItem, - AutocompleteOptions, - AutocompleteRequest, - AutocompleteResult, - DebugInfo, - DocumentDebugInfo, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - FacetResult, - HybridSearch, - IndexAction, - IndexBatch, - IndexDocumentsResult, - IndexingResult, - QueryAnswerResult, - QueryCaptionResult, - QueryResultDocumentInnerHit, - QueryResultDocumentRerankerInput, - QueryResultDocumentSemanticField, - QueryResultDocumentSubscores, - QueryRewritesDebugInfo, - QueryRewritesValuesDebugInfo, - RequestOptions, - SearchDocumentsResult, - SearchOptions, - SearchRequest, - SearchResult, - SearchScoreThreshold, - SemanticDebugInfo, - SingleVectorFieldResult, - SuggestDocumentsResult, - SuggestOptions, - SuggestRequest, - SuggestResult, - TextResult, - VectorQuery, - VectorSimilarityThreshold, - VectorThreshold, - VectorizableImageBinaryQuery, - VectorizableImageUrlQuery, - VectorizableTextQuery, - VectorizedQuery, - VectorsDebugInfo, -) - -from ._search_index_client_enums import ( # type: ignore - AutocompleteMode, - HybridCountAndFacetMode, - IndexActionType, - QueryAnswerType, - QueryCaptionType, - QueryDebugMode, - QueryLanguage, - QueryRewritesType, - QuerySpellerType, - QueryType, - ScoringStatistics, - SearchMode, - SemanticErrorMode, - SemanticErrorReason, - SemanticFieldState, - SemanticQueryRewritesResultType, - SemanticSearchResultsType, - VectorFilterMode, - VectorQueryKind, - VectorThresholdKind, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AutocompleteItem", - "AutocompleteOptions", - "AutocompleteRequest", - "AutocompleteResult", - "DebugInfo", - "DocumentDebugInfo", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "FacetResult", - "HybridSearch", - "IndexAction", - "IndexBatch", - "IndexDocumentsResult", - "IndexingResult", - "QueryAnswerResult", - "QueryCaptionResult", - "QueryResultDocumentInnerHit", - "QueryResultDocumentRerankerInput", - "QueryResultDocumentSemanticField", - "QueryResultDocumentSubscores", - "QueryRewritesDebugInfo", - "QueryRewritesValuesDebugInfo", - "RequestOptions", - "SearchDocumentsResult", - "SearchOptions", - "SearchRequest", - "SearchResult", - "SearchScoreThreshold", - "SemanticDebugInfo", - "SingleVectorFieldResult", - "SuggestDocumentsResult", - "SuggestOptions", - "SuggestRequest", - "SuggestResult", - "TextResult", - "VectorQuery", - "VectorSimilarityThreshold", - "VectorThreshold", - "VectorizableImageBinaryQuery", - "VectorizableImageUrlQuery", - "VectorizableTextQuery", - "VectorizedQuery", - "VectorsDebugInfo", - "AutocompleteMode", - "HybridCountAndFacetMode", - "IndexActionType", - "QueryAnswerType", - "QueryCaptionType", - "QueryDebugMode", - "QueryLanguage", - "QueryRewritesType", - "QuerySpellerType", - "QueryType", - "ScoringStatistics", - "SearchMode", - "SemanticErrorMode", - "SemanticErrorReason", - "SemanticFieldState", - "SemanticQueryRewritesResultType", - "SemanticSearchResultsType", - "VectorFilterMode", - "VectorQueryKind", - "VectorThresholdKind", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py deleted file mode 100644 index 4e74e0b6cc7a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models_py3.py +++ /dev/null @@ -1,3098 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional, TYPE_CHECKING, Union, MutableMapping - -from .._utils import serialization as _serialization - -JSON = MutableMapping[str, Any] - -if TYPE_CHECKING: - from .. import models as _models - - -class AutocompleteItem(_serialization.Model): - """The result of Autocomplete requests. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar text: The completed term. Required. - :vartype text: str - :ivar query_plus_text: The query along with the completed term. Required. - :vartype query_plus_text: str - """ - - _validation = { - "text": {"required": True, "readonly": True}, - "query_plus_text": {"required": True, "readonly": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "str"}, - "query_plus_text": {"key": "queryPlusText", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.text: Optional[str] = None - self.query_plus_text: Optional[str] = None - - -class AutocompleteOptions(_serialization.Model): - """Parameter group. - - :ivar autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :vartype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :ivar filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the autocomplete - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :vartype search_fields: list[str] - :ivar top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :vartype top: int - """ - - _attribute_map = { - "autocomplete_mode": {"key": "autocompleteMode", "type": "str"}, - "filter": {"key": "$filter", "type": "str"}, - "use_fuzzy_matching": {"key": "UseFuzzyMatching", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "search_fields": {"key": "searchFields", "type": "[str]"}, - "top": {"key": "$top", "type": "int"}, - } - - def __init__( - self, - *, - autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[list[str]] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by an autocomplete query in order for the query to be reported as a - success. This parameter can be useful for ensuring search availability even for services with - only one replica. The default is 80. - :paramtype minimum_coverage: float - :keyword search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :paramtype search_fields: list[str] - :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 - and 100. The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.autocomplete_mode = autocomplete_mode - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.search_fields = search_fields - self.top = top - - -class AutocompleteRequest(_serialization.Model): - """Parameters for fuzzy matching, and other autocomplete query behaviors. - - All required parameters must be populated in order to send to server. - - :ivar search_text: The search text on which to base autocomplete results. Required. - :vartype search_text: str - :ivar autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :vartype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :ivar filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the autocomplete - query. Default is false. When set to true, the query will autocomplete terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. - :vartype search_fields: str - :ivar suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :vartype suggester_name: str - :ivar top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :vartype top: int - """ - - _validation = { - "search_text": {"required": True}, - "suggester_name": {"required": True}, - } - - _attribute_map = { - "search_text": {"key": "search", "type": "str"}, - "autocomplete_mode": {"key": "autocompleteMode", "type": "str"}, - "filter": {"key": "filter", "type": "str"}, - "use_fuzzy_matching": {"key": "fuzzy", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "search_fields": {"key": "searchFields", "type": "str"}, - "suggester_name": {"key": "suggesterName", "type": "str"}, - "top": {"key": "top", "type": "int"}, - } - - def __init__( - self, - *, - search_text: str, - suggester_name: str, - autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword search_text: The search text on which to base autocomplete results. Required. - :paramtype search_text: str - :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will autocomplete terms even - if there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by an autocomplete query in order for the query to be reported as a - success. This parameter can be useful for ensuring search availability even for services with - only one replica. The default is 80. - :paramtype minimum_coverage: float - :keyword search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. - :paramtype search_fields: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 - and 100. The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.search_text = search_text - self.autocomplete_mode = autocomplete_mode - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.search_fields = search_fields - self.suggester_name = suggester_name - self.top = top - - -class AutocompleteResult(_serialization.Model): - """The result of Autocomplete query. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar coverage: A value indicating the percentage of the index that was considered by the - autocomplete request, or null if minimumCoverage was not specified in the request. - :vartype coverage: float - :ivar results: The list of returned Autocompleted items. Required. - :vartype results: list[~azure.search.documents.models.AutocompleteItem] - """ - - _validation = { - "coverage": {"readonly": True}, - "results": {"required": True, "readonly": True}, - } - - _attribute_map = { - "coverage": {"key": "@search\\.coverage", "type": "float"}, - "results": {"key": "value", "type": "[AutocompleteItem]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.coverage: Optional[float] = None - self.results: Optional[list["_models.AutocompleteItem"]] = None - - -class DebugInfo(_serialization.Model): - """Contains debugging information that can be used to further explore your search results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar query_rewrites: Contains debugging information specific to query rewrites. - :vartype query_rewrites: ~azure.search.documents.models.QueryRewritesDebugInfo - """ - - _validation = { - "query_rewrites": {"readonly": True}, - } - - _attribute_map = { - "query_rewrites": {"key": "queryRewrites", "type": "QueryRewritesDebugInfo"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.query_rewrites: Optional["_models.QueryRewritesDebugInfo"] = None - - -class DocumentDebugInfo(_serialization.Model): - """Contains debugging information that can be used to further explore your search results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar semantic: Contains debugging information specific to semantic ranking requests. - :vartype semantic: ~azure.search.documents.models.SemanticDebugInfo - :ivar vectors: Contains debugging information specific to vector and hybrid search. - :vartype vectors: ~azure.search.documents.models.VectorsDebugInfo - :ivar inner_hits: Contains debugging information specific to vectors matched within a - collection of complex types. - :vartype inner_hits: dict[str, - list[~azure.search.documents.models.QueryResultDocumentInnerHit]] - """ - - _validation = { - "semantic": {"readonly": True}, - "vectors": {"readonly": True}, - "inner_hits": {"readonly": True}, - } - - _attribute_map = { - "semantic": {"key": "semantic", "type": "SemanticDebugInfo"}, - "vectors": {"key": "vectors", "type": "VectorsDebugInfo"}, - "inner_hits": {"key": "innerHits", "type": "{[QueryResultDocumentInnerHit]}"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.semantic: Optional["_models.SemanticDebugInfo"] = None - self.vectors: Optional["_models.VectorsDebugInfo"] = None - self.inner_hits: Optional[dict[str, list["_models.QueryResultDocumentInnerHit"]]] = None - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.search.documents.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.search.documents.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.search.documents.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class FacetResult(_serialization.Model): - """A single bucket of a facet query result. Reports the number of documents with a field value - falling within a particular range or having a particular value or interval. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar count: The approximate count of documents falling within the bucket described by this - facet. - :vartype count: int - :ivar sum: The resulting total sum for the facet when a sum metric is requested. - :vartype sum: float - :ivar facets: The nested facet query results for the search operation, organized as a - collection of buckets for each faceted field; null if the query did not contain any nested - facets. - :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] - """ - - _validation = { - "count": {"readonly": True}, - "sum": {"readonly": True}, - "facets": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "count": {"key": "count", "type": "int"}, - "sum": {"key": "sum", "type": "float"}, - "facets": {"key": "@search\\.facets", "type": "{[FacetResult]}"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.count: Optional[int] = None - self.sum: Optional[float] = None - self.facets: Optional[dict[str, list["_models.FacetResult"]]] = None - - -class HybridSearch(_serialization.Model): - """TThe query parameters to configure hybrid search behaviors. - - :ivar max_text_recall_size: Determines the maximum number of documents to be retrieved by the - text query portion of a hybrid search request. Those documents will be combined with the - documents matching the vector queries to produce a single final list of results. Choosing a - larger maxTextRecallSize value will allow retrieving and paging through more documents (using - the top and skip parameters), at the cost of higher resource utilization and higher latency. - The value needs to be between 1 and 10,000. Default is 1000. - :vartype max_text_recall_size: int - :ivar count_and_facet_mode: Determines whether the count and facets should includes all - documents that matched the search query, or only the documents that are retrieved within the - 'maxTextRecallSize' window. Known values are: "countRetrievableResults" and "countAllResults". - :vartype count_and_facet_mode: str or ~azure.search.documents.models.HybridCountAndFacetMode - """ - - _attribute_map = { - "max_text_recall_size": {"key": "maxTextRecallSize", "type": "int"}, - "count_and_facet_mode": {"key": "countAndFacetMode", "type": "str"}, - } - - def __init__( - self, - *, - max_text_recall_size: Optional[int] = None, - count_and_facet_mode: Optional[Union[str, "_models.HybridCountAndFacetMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword max_text_recall_size: Determines the maximum number of documents to be retrieved by - the text query portion of a hybrid search request. Those documents will be combined with the - documents matching the vector queries to produce a single final list of results. Choosing a - larger maxTextRecallSize value will allow retrieving and paging through more documents (using - the top and skip parameters), at the cost of higher resource utilization and higher latency. - The value needs to be between 1 and 10,000. Default is 1000. - :paramtype max_text_recall_size: int - :keyword count_and_facet_mode: Determines whether the count and facets should includes all - documents that matched the search query, or only the documents that are retrieved within the - 'maxTextRecallSize' window. Known values are: "countRetrievableResults" and "countAllResults". - :paramtype count_and_facet_mode: str or ~azure.search.documents.models.HybridCountAndFacetMode - """ - super().__init__(**kwargs) - self.max_text_recall_size = max_text_recall_size - self.count_and_facet_mode = count_and_facet_mode - - -class IndexAction(_serialization.Model): - """Represents an index action that operates on a document. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar action_type: The operation to perform on a document in an indexing batch. Known values - are: "upload", "merge", "mergeOrUpload", and "delete". - :vartype action_type: str or ~azure.search.documents.models.IndexActionType - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "action_type": {"key": "@search\\.action", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - action_type: Optional[Union[str, "_models.IndexActionType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword action_type: The operation to perform on a document in an indexing batch. Known values - are: "upload", "merge", "mergeOrUpload", and "delete". - :paramtype action_type: str or ~azure.search.documents.models.IndexActionType - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.action_type = action_type - - -class IndexBatch(_serialization.Model): - """Contains a batch of document write actions to send to the index. - - All required parameters must be populated in order to send to server. - - :ivar actions: The actions in the batch. Required. - :vartype actions: list[~azure.search.documents.models.IndexAction] - """ - - _validation = { - "actions": {"required": True}, - } - - _attribute_map = { - "actions": {"key": "value", "type": "[IndexAction]"}, - } - - def __init__(self, *, actions: list["_models.IndexAction"], **kwargs: Any) -> None: - """ - :keyword actions: The actions in the batch. Required. - :paramtype actions: list[~azure.search.documents.models.IndexAction] - """ - super().__init__(**kwargs) - self.actions = actions - - -class IndexDocumentsResult(_serialization.Model): - """Response containing the status of operations for all documents in the indexing request. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar results: The list of status information for each document in the indexing request. - Required. - :vartype results: list[~azure.search.documents.models.IndexingResult] - """ - - _validation = { - "results": {"required": True, "readonly": True}, - } - - _attribute_map = { - "results": {"key": "value", "type": "[IndexingResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.results: Optional[list["_models.IndexingResult"]] = None - - -class IndexingResult(_serialization.Model): - """Status of an indexing operation for a single document. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar key: The key of a document that was in the indexing request. Required. - :vartype key: str - :ivar error_message: The error message explaining why the indexing operation failed for the - document identified by the key; null if indexing succeeded. - :vartype error_message: str - :ivar succeeded: A value indicating whether the indexing operation succeeded for the document - identified by the key. Required. - :vartype succeeded: bool - :ivar status_code: The status code of the indexing operation. Possible values include: 200 for - a successful update or delete, 201 for successful document creation, 400 for a malformed input - document, 404 for document not found, 409 for a version conflict, 422 when the index is - temporarily unavailable, or 503 for when the service is too busy. Required. - :vartype status_code: int - """ - - _validation = { - "key": {"required": True, "readonly": True}, - "error_message": {"readonly": True}, - "succeeded": {"required": True, "readonly": True}, - "status_code": {"required": True, "readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "error_message": {"key": "errorMessage", "type": "str"}, - "succeeded": {"key": "status", "type": "bool"}, - "status_code": {"key": "statusCode", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.key: Optional[str] = None - self.error_message: Optional[str] = None - self.succeeded: Optional[bool] = None - self.status_code: Optional[int] = None - - -class QueryAnswerResult(_serialization.Model): - """An answer is a text passage extracted from the contents of the most relevant documents that - matched the query. Answers are extracted from the top search results. Answer candidates are - scored and the top answers are selected. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar score: The score value represents how relevant the answer is to the query relative to - other answers returned for the query. - :vartype score: float - :ivar key: The key of the document the answer was extracted from. - :vartype key: str - :ivar text: The text passage extracted from the document contents as the answer. - :vartype text: str - :ivar highlights: Same text passage as in the Text property with highlighted text phrases most - relevant to the query. - :vartype highlights: str - """ - - _validation = { - "score": {"readonly": True}, - "key": {"readonly": True}, - "text": {"readonly": True}, - "highlights": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "score": {"key": "score", "type": "float"}, - "key": {"key": "key", "type": "str"}, - "text": {"key": "text", "type": "str"}, - "highlights": {"key": "highlights", "type": "str"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.score: Optional[float] = None - self.key: Optional[str] = None - self.text: Optional[str] = None - self.highlights: Optional[str] = None - - -class QueryCaptionResult(_serialization.Model): - """Captions are the most representative passages from the document relatively to the search query. - They are often used as document summary. Captions are only returned for queries of type - ``semantic``. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar text: A representative text passage extracted from the document most relevant to the - search query. - :vartype text: str - :ivar highlights: Same text passage as in the Text property with highlighted phrases most - relevant to the query. - :vartype highlights: str - """ - - _validation = { - "text": {"readonly": True}, - "highlights": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "text": {"key": "text", "type": "str"}, - "highlights": {"key": "highlights", "type": "str"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.text: Optional[str] = None - self.highlights: Optional[str] = None - - -class QueryResultDocumentInnerHit(_serialization.Model): - """Detailed scoring information for an individual element of a complex collection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar ordinal: Position of this specific matching element within it's original collection. - Position starts at 0. - :vartype ordinal: int - :ivar vectors: Detailed scoring information for an individual element of a complex collection - that matched a vector query. - :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] - """ - - _validation = { - "ordinal": {"readonly": True}, - "vectors": {"readonly": True}, - } - - _attribute_map = { - "ordinal": {"key": "ordinal", "type": "int"}, - "vectors": {"key": "vectors", "type": "[{SingleVectorFieldResult}]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.ordinal: Optional[int] = None - self.vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = None - - -class QueryResultDocumentRerankerInput(_serialization.Model): - """The raw concatenated strings that were sent to the semantic enrichment process. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar title: The raw string for the title field that was used for semantic enrichment. - :vartype title: str - :ivar content: The raw concatenated strings for the content fields that were used for semantic - enrichment. - :vartype content: str - :ivar keywords: The raw concatenated strings for the keyword fields that were used for semantic - enrichment. - :vartype keywords: str - """ - - _validation = { - "title": {"readonly": True}, - "content": {"readonly": True}, - "keywords": {"readonly": True}, - } - - _attribute_map = { - "title": {"key": "title", "type": "str"}, - "content": {"key": "content", "type": "str"}, - "keywords": {"key": "keywords", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.title: Optional[str] = None - self.content: Optional[str] = None - self.keywords: Optional[str] = None - - -class QueryResultDocumentSemanticField(_serialization.Model): - """Description of fields that were sent to the semantic enrichment process, as well as how they - were used. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the field that was sent to the semantic enrichment process. - :vartype name: str - :ivar state: The way the field was used for the semantic enrichment process (fully used, - partially used, or unused). Known values are: "used", "unused", and "partial". - :vartype state: str or ~azure.search.documents.models.SemanticFieldState - """ - - _validation = { - "name": {"readonly": True}, - "state": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "state": {"key": "state", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.state: Optional[Union[str, "_models.SemanticFieldState"]] = None - - -class QueryResultDocumentSubscores(_serialization.Model): - """The breakdown of subscores between the text and vector query components of the search query for - this document. Each vector query is shown as a separate object in the same order they were - received. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar text: The BM25 or Classic score for the text portion of the query. - :vartype text: ~azure.search.documents.models.TextResult - :ivar vectors: The vector similarity and @search.score values for each vector query. - :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] - :ivar document_boost: The BM25 or Classic score for the text portion of the query. - :vartype document_boost: float - """ - - _validation = { - "text": {"readonly": True}, - "vectors": {"readonly": True}, - "document_boost": {"readonly": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "TextResult"}, - "vectors": {"key": "vectors", "type": "[{SingleVectorFieldResult}]"}, - "document_boost": {"key": "documentBoost", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.text: Optional["_models.TextResult"] = None - self.vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = None - self.document_boost: Optional[float] = None - - -class QueryRewritesDebugInfo(_serialization.Model): - """Contains debugging information specific to query rewrites. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar text: List of query rewrites generated for the text query. - :vartype text: ~azure.search.documents.models.QueryRewritesValuesDebugInfo - :ivar vectors: List of query rewrites generated for the vectorizable text queries. - :vartype vectors: list[~azure.search.documents.models.QueryRewritesValuesDebugInfo] - """ - - _validation = { - "text": {"readonly": True}, - "vectors": {"readonly": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "QueryRewritesValuesDebugInfo"}, - "vectors": {"key": "vectors", "type": "[QueryRewritesValuesDebugInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.text: Optional["_models.QueryRewritesValuesDebugInfo"] = None - self.vectors: Optional[list["_models.QueryRewritesValuesDebugInfo"]] = None - - -class QueryRewritesValuesDebugInfo(_serialization.Model): - """Contains debugging information specific to query rewrites. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar input_query: The input text to the generative query rewriting model. There may be cases - where the user query and the input to the generative model are not identical. - :vartype input_query: str - :ivar rewrites: List of query rewrites. - :vartype rewrites: list[str] - """ - - _validation = { - "input_query": {"readonly": True}, - "rewrites": {"readonly": True}, - } - - _attribute_map = { - "input_query": {"key": "inputQuery", "type": "str"}, - "rewrites": {"key": "rewrites", "type": "[str]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.input_query: Optional[str] = None - self.rewrites: Optional[list[str]] = None - - -class RequestOptions(_serialization.Model): - """Parameter group. - - :ivar x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :vartype x_ms_client_request_id: str - """ - - _attribute_map = { - "x_ms_client_request_id": {"key": "x-ms-client-request-id", "type": "str"}, - } - - def __init__(self, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :paramtype x_ms_client_request_id: str - """ - super().__init__(**kwargs) - self.x_ms_client_request_id = x_ms_client_request_id - - -class SearchDocumentsResult(_serialization.Model): - """Response containing search results from an index. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar count: The total count of results found by the search operation, or null if the count was - not requested. If present, the count may be greater than the number of results in this - response. This can happen if you use the $top or $skip parameters, or if the query can't return - all the requested documents in a single response. - :vartype count: int - :ivar coverage: A value indicating the percentage of the index that was included in the query, - or null if minimumCoverage was not specified in the request. - :vartype coverage: float - :ivar facets: The facet query results for the search operation, organized as a collection of - buckets for each faceted field; null if the query did not include any facet expressions. - :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] - :ivar answers: The answers query results for the search operation; null if the answers query - parameter was not specified or set to 'none'. - :vartype answers: list[~azure.search.documents.models.QueryAnswerResult] - :ivar debug_info: Debug information that applies to the search results as a whole. - :vartype debug_info: ~azure.search.documents.models.DebugInfo - :ivar next_page_parameters: Continuation JSON payload returned when the query can't return all - the requested results in a single response. You can use this JSON along with @odata.nextLink to - formulate another POST Search request to get the next part of the search response. - :vartype next_page_parameters: ~azure.search.documents.models.SearchRequest - :ivar results: The sequence of results returned by the query. Required. - :vartype results: list[~azure.search.documents.models.SearchResult] - :ivar next_link: Continuation URL returned when the query can't return all the requested - results in a single response. You can use this URL to formulate another GET or POST Search - request to get the next part of the search response. Make sure to use the same verb (GET or - POST) as the request that produced this response. - :vartype next_link: str - :ivar semantic_partial_response_reason: Reason that a partial response was returned for a - semantic ranking request. Known values are: "maxWaitExceeded", "capacityOverloaded", and - "transient". - :vartype semantic_partial_response_reason: str or - ~azure.search.documents.models.SemanticErrorReason - :ivar semantic_partial_response_type: Type of partial response that was returned for a semantic - ranking request. Known values are: "baseResults" and "rerankedResults". - :vartype semantic_partial_response_type: str or - ~azure.search.documents.models.SemanticSearchResultsType - :ivar semantic_query_rewrites_result_type: Type of query rewrite that was used to retrieve - documents. "originalQueryOnly" - :vartype semantic_query_rewrites_result_type: str or - ~azure.search.documents.models.SemanticQueryRewritesResultType - """ - - _validation = { - "count": {"readonly": True}, - "coverage": {"readonly": True}, - "facets": {"readonly": True}, - "answers": {"readonly": True}, - "debug_info": {"readonly": True}, - "next_page_parameters": {"readonly": True}, - "results": {"required": True, "readonly": True}, - "next_link": {"readonly": True}, - "semantic_partial_response_reason": {"readonly": True}, - "semantic_partial_response_type": {"readonly": True}, - "semantic_query_rewrites_result_type": {"readonly": True}, - } - - _attribute_map = { - "count": {"key": "@odata\\.count", "type": "int"}, - "coverage": {"key": "@search\\.coverage", "type": "float"}, - "facets": {"key": "@search\\.facets", "type": "{[FacetResult]}"}, - "answers": {"key": "@search\\.answers", "type": "[QueryAnswerResult]"}, - "debug_info": {"key": "@search\\.debug", "type": "DebugInfo"}, - "next_page_parameters": {"key": "@search\\.nextPageParameters", "type": "SearchRequest"}, - "results": {"key": "value", "type": "[SearchResult]"}, - "next_link": {"key": "@odata\\.nextLink", "type": "str"}, - "semantic_partial_response_reason": {"key": "@search\\.semanticPartialResponseReason", "type": "str"}, - "semantic_partial_response_type": {"key": "@search\\.semanticPartialResponseType", "type": "str"}, - "semantic_query_rewrites_result_type": {"key": "@search\\.semanticQueryRewritesResultType", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.count: Optional[int] = None - self.coverage: Optional[float] = None - self.facets: Optional[dict[str, list["_models.FacetResult"]]] = None - self.answers: Optional[list["_models.QueryAnswerResult"]] = None - self.debug_info: Optional["_models.DebugInfo"] = None - self.next_page_parameters: Optional["_models.SearchRequest"] = None - self.results: Optional[list["_models.SearchResult"]] = None - self.next_link: Optional[str] = None - self.semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = None - self.semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = None - self.semantic_query_rewrites_result_type: Optional[Union[str, "_models.SemanticQueryRewritesResultType"]] = None - - -class SearchOptions(_serialization.Model): - """Parameter group. - - :ivar include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :vartype include_total_result_count: bool - :ivar facets: The list of facet expressions to apply to the search query. Each facet expression - contains a field name, optionally followed by a comma-separated list of name:value pairs. - :vartype facets: list[str] - :ivar filter: The OData $filter expression to apply to the search query. - :vartype filter: str - :ivar highlight_fields: The list of field names to use for hit highlights. Only searchable - fields can be used for hit highlighting. - :vartype highlight_fields: list[str] - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :vartype minimum_coverage: float - :ivar order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: list[str] - :ivar query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :vartype query_type: str or ~azure.search.documents.models.QueryType - :ivar scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :vartype scoring_parameters: list[str] - :ivar scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :vartype scoring_profile: str - :ivar search_fields: The list of field names to which to scope the full-text search. When using - fielded search (fieldName:searchExpression) in a full Lucene query, the field names of each - fielded search expression take precedence over any field names listed in this parameter. - :vartype search_fields: list[str] - :ivar search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :vartype search_mode: str or ~azure.search.documents.models.SearchMode - :ivar scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. Known values are: "local", "global", and "global". - :vartype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :ivar session_id: A value to be used to create a sticky session, which can help to get more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :vartype session_id: str - :ivar select: The list of fields to retrieve. If unspecified, all fields marked as retrievable - in the schema are included. - :vartype select: list[str] - :ivar skip: The number of search results to skip. This value cannot be greater than 100,000. If - you need to scan documents in sequence, but cannot use $skip due to this limitation, consider - using $orderby on a totally-ordered key and $filter with a range query instead. - :vartype skip: int - :ivar top: The number of search results to retrieve. This can be used in conjunction with $skip - to implement client-side paging of search results. If results are truncated due to server-side - paging, the response will include a continuation token that can be used to issue another Search - request for the next page of results. - :vartype top: int - :ivar semantic_configuration: The name of the semantic configuration that lists which fields - should be used for semantic ranking, captions, highlights, and answers. - :vartype semantic_configuration: str - :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely, or to return partial results (default). Known values are: "partial" and "fail". - :vartype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :ivar semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :vartype semantic_max_wait_in_milliseconds: int - :ivar answers: This parameter is only valid if the query type is ``semantic``. If set, the - query returns answers extracted from key passages in the highest ranked documents. The number - of answers returned can be configured by appending the pipe character ``|`` followed by the - ``count-`` option after the answers parameter value, such as - ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by - appending the pipe character ``|`` followed by the ``threshold-`` option - after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is - 0.7. The maximum character length of answers can be configured by appending the pipe character - '|' followed by the 'count-\\ :code:``', such as - 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". - :vartype answers: str or ~azure.search.documents.models.QueryAnswerType - :ivar captions: This parameter is only valid if the query type is ``semantic``. If set, the - query returns captions extracted from key passages in the highest ranked documents. When - Captions is set to ``extractive``\\ , highlighting is enabled by default, and can be configured - by appending the pipe character ``|`` followed by the ``highlight-`` option, such - as ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of - captions can be configured by appending the pipe character '|' followed by the 'count-\\ - :code:``', such as 'extractive|maxcharlength-600'. Known - values are: "none" and "extractive". - :vartype captions: str or ~azure.search.documents.models.QueryCaptionType - :ivar semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :vartype semantic_query: str - :ivar query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent - to a generate model which will produce 10 (default) rewrites to help increase the recall of the - request. The requested count can be configured by appending the pipe character ``|`` followed - by the ``count-`` option, such as ``generative|count-3``. Defaults to - ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :ivar debug: Enables a debugging tool that can be used to further explore your search results. - Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and "all". - :vartype debug: str or ~azure.search.documents.models.QueryDebugMode - :ivar query_language: The language of the query. Known values are: "none", "en-us", "en-gb", - "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", - "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", - "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", - "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", - "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", - "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", - "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". - :vartype query_language: str or ~azure.search.documents.models.QueryLanguage - :ivar speller: Improve search recall by spell-correcting individual search query terms. Known - values are: "none" and "lexicon". - :vartype speller: str or ~azure.search.documents.models.QuerySpellerType - :ivar semantic_fields: The list of field names used for semantic ranking. - :vartype semantic_fields: list[str] - """ - - _validation = { - "semantic_max_wait_in_milliseconds": {"minimum": 700}, - } - - _attribute_map = { - "include_total_result_count": {"key": "IncludeTotalResultCount", "type": "bool"}, - "facets": {"key": "Facets", "type": "[str]"}, - "filter": {"key": "$filter", "type": "str"}, - "highlight_fields": {"key": "HighlightFields", "type": "[str]"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "OrderBy", "type": "[str]"}, - "query_type": {"key": "queryType", "type": "str"}, - "scoring_parameters": {"key": "ScoringParameters", "type": "[str]"}, - "scoring_profile": {"key": "scoringProfile", "type": "str"}, - "search_fields": {"key": "searchFields", "type": "[str]"}, - "search_mode": {"key": "searchMode", "type": "str"}, - "scoring_statistics": {"key": "scoringStatistics", "type": "str"}, - "session_id": {"key": "sessionId", "type": "str"}, - "select": {"key": "$select", "type": "[str]"}, - "skip": {"key": "$skip", "type": "int"}, - "top": {"key": "$top", "type": "int"}, - "semantic_configuration": {"key": "semanticConfiguration", "type": "str"}, - "semantic_error_handling": {"key": "semanticErrorHandling", "type": "str"}, - "semantic_max_wait_in_milliseconds": {"key": "semanticMaxWaitInMilliseconds", "type": "int"}, - "answers": {"key": "answers", "type": "str"}, - "captions": {"key": "captions", "type": "str"}, - "semantic_query": {"key": "semanticQuery", "type": "str"}, - "query_rewrites": {"key": "queryRewrites", "type": "str"}, - "debug": {"key": "debug", "type": "str"}, - "query_language": {"key": "queryLanguage", "type": "str"}, - "speller": {"key": "speller", "type": "str"}, - "semantic_fields": {"key": "semanticFields", "type": "[str]"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - include_total_result_count: Optional[bool] = None, - facets: Optional[list[str]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - highlight_fields: Optional[list[str]] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - query_type: Optional[Union[str, "_models.QueryType"]] = None, - scoring_parameters: Optional[list[str]] = None, - scoring_profile: Optional[str] = None, - search_fields: Optional[list[str]] = None, - search_mode: Optional[Union[str, "_models.SearchMode"]] = None, - scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = None, - session_id: Optional[str] = None, - select: Optional[list[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - semantic_configuration: Optional[str] = None, - semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - answers: Optional[Union[str, "_models.QueryAnswerType"]] = None, - captions: Optional[Union[str, "_models.QueryCaptionType"]] = None, - semantic_query: Optional[str] = None, - query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, - debug: Optional[Union[str, "_models.QueryDebugMode"]] = None, - query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, - speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, - semantic_fields: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :paramtype include_total_result_count: bool - :keyword facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :paramtype facets: list[str] - :keyword filter: The OData $filter expression to apply to the search query. - :paramtype filter: str - :keyword highlight_fields: The list of field names to use for hit highlights. Only searchable - fields can be used for hit highlighting. - :paramtype highlight_fields: list[str] - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :paramtype minimum_coverage: float - :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :paramtype order_by: list[str] - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :paramtype scoring_parameters: list[str] - :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :paramtype scoring_profile: str - :keyword search_fields: The list of field names to which to scope the full-text search. When - using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of - each fielded search expression take precedence over any field names listed in this parameter. - :paramtype search_fields: list[str] - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. Known values are: "local", "global", and "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword session_id: A value to be used to create a sticky session, which can help to get more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :paramtype session_id: str - :keyword select: The list of fields to retrieve. If unspecified, all fields marked as - retrievable in the schema are included. - :paramtype select: list[str] - :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use $skip due to this limitation, - consider using $orderby on a totally-ordered key and $filter with a range query instead. - :paramtype skip: int - :keyword top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :paramtype top: int - :keyword semantic_configuration: The name of the semantic configuration that lists which fields - should be used for semantic ranking, captions, highlights, and answers. - :paramtype semantic_configuration: str - :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely, or to return partial results (default). Known values are: "partial" and "fail". - :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount - of time it takes for semantic enrichment to finish processing before the request fails. - :paramtype semantic_max_wait_in_milliseconds: int - :keyword answers: This parameter is only valid if the query type is ``semantic``. If set, the - query returns answers extracted from key passages in the highest ranked documents. The number - of answers returned can be configured by appending the pipe character ``|`` followed by the - ``count-`` option after the answers parameter value, such as - ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by - appending the pipe character ``|`` followed by the ``threshold-`` option - after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is - 0.7. The maximum character length of answers can be configured by appending the pipe character - '|' followed by the 'count-\\ :code:``', such as - 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". - :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType - :keyword captions: This parameter is only valid if the query type is ``semantic``. If set, the - query returns captions extracted from key passages in the highest ranked documents. When - Captions is set to ``extractive``\\ , highlighting is enabled by default, and can be configured - by appending the pipe character ``|`` followed by the ``highlight-`` option, such - as ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of - captions can be configured by appending the pipe character '|' followed by the 'count-\\ - :code:``', such as 'extractive|maxcharlength-600'. Known - values are: "none" and "extractive". - :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType - :keyword semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :paramtype semantic_query: str - :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are - sent to a generate model which will produce 10 (default) rewrites to help increase the recall - of the request. The requested count can be configured by appending the pipe character ``|`` - followed by the ``count-`` option, such as ``generative|count-3``. Defaults - to ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword debug: Enables a debugging tool that can be used to further explore your search - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword query_language: The language of the query. Known values are: "none", "en-us", "en-gb", - "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", - "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", - "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", - "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", - "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", - "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", - "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword speller: Improve search recall by spell-correcting individual search query terms. - Known values are: "none" and "lexicon". - :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword semantic_fields: The list of field names used for semantic ranking. - :paramtype semantic_fields: list[str] - """ - super().__init__(**kwargs) - self.include_total_result_count = include_total_result_count - self.facets = facets - self.filter = filter - self.highlight_fields = highlight_fields - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.query_type = query_type - self.scoring_parameters = scoring_parameters - self.scoring_profile = scoring_profile - self.search_fields = search_fields - self.search_mode = search_mode - self.scoring_statistics = scoring_statistics - self.session_id = session_id - self.select = select - self.skip = skip - self.top = top - self.semantic_configuration = semantic_configuration - self.semantic_error_handling = semantic_error_handling - self.semantic_max_wait_in_milliseconds = semantic_max_wait_in_milliseconds - self.answers = answers - self.captions = captions - self.semantic_query = semantic_query - self.query_rewrites = query_rewrites - self.debug = debug - self.query_language = query_language - self.speller = speller - self.semantic_fields = semantic_fields - - -class SearchRequest(_serialization.Model): - """Parameters for filtering, sorting, faceting, paging, and other search query behaviors. - - :ivar include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :vartype include_total_result_count: bool - :ivar facets: The list of facet expressions to apply to the search query. Each facet expression - contains a field name, optionally followed by a comma-separated list of name:value pairs. - :vartype facets: list[str] - :ivar filter: The OData $filter expression to apply to the search query. - :vartype filter: str - :ivar highlight_fields: The comma-separated list of field names to use for hit highlights. Only - searchable fields can be used for hit highlighting. - :vartype highlight_fields: str - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :vartype minimum_coverage: float - :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: str - :ivar query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :vartype query_type: str or ~azure.search.documents.models.QueryType - :ivar scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. Known - values are: "local", "global", and "global". - :vartype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :ivar session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :vartype session_id: str - :ivar scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :vartype scoring_parameters: list[str] - :ivar scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :vartype scoring_profile: str - :ivar debug: Enables a debugging tool that can be used to further explore your reranked - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". - :vartype debug: str or ~azure.search.documents.models.QueryDebugMode - :ivar search_text: A full-text search query expression; Use "*" or omit this parameter to match - all documents. - :vartype search_text: str - :ivar search_fields: The comma-separated list of field names to which to scope the full-text - search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the - field names of each fielded search expression take precedence over any field names listed in - this parameter. - :vartype search_fields: str - :ivar search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :vartype search_mode: str or ~azure.search.documents.models.SearchMode - :ivar query_language: A value that specifies the language of the search query. Known values - are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", - "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", - "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", - "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", - "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", - "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", - "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", - "te-in", and "ur-pk". - :vartype query_language: str or ~azure.search.documents.models.QueryLanguage - :ivar speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Known values are: "none" and "lexicon". - :vartype speller: str or ~azure.search.documents.models.QuerySpellerType - :ivar select: The comma-separated list of fields to retrieve. If unspecified, all fields marked - as retrievable in the schema are included. - :vartype select: str - :ivar skip: The number of search results to skip. This value cannot be greater than 100,000. If - you need to scan documents in sequence, but cannot use skip due to this limitation, consider - using orderby on a totally-ordered key and filter with a range query instead. - :vartype skip: int - :ivar top: The number of search results to retrieve. This can be used in conjunction with $skip - to implement client-side paging of search results. If results are truncated due to server-side - paging, the response will include a continuation token that can be used to issue another Search - request for the next page of results. - :vartype top: int - :ivar semantic_configuration: The name of a semantic configuration that will be used when - processing documents for queries of type semantic. - :vartype semantic_configuration: str - :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :vartype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :ivar semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :vartype semantic_max_wait_in_milliseconds: int - :ivar semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :vartype semantic_query: str - :ivar answers: A value that specifies whether answers should be returned as part of the search - response. Known values are: "none" and "extractive". - :vartype answers: str or ~azure.search.documents.models.QueryAnswerType - :ivar captions: A value that specifies whether captions should be returned as part of the - search response. Known values are: "none" and "extractive". - :vartype captions: str or ~azure.search.documents.models.QueryCaptionType - :ivar query_rewrites: A value that specifies whether query rewrites should be generated to - augment the search query. Known values are: "none" and "generative". - :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :ivar semantic_fields: The comma-separated list of field names used for semantic ranking. - :vartype semantic_fields: str - :ivar vector_queries: The query parameters for vector and hybrid search queries. - :vartype vector_queries: list[~azure.search.documents.models.VectorQuery] - :ivar vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter' for new indexes. Known values are: - "postFilter", "preFilter", and "strictPostFilter". - :vartype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode - :ivar hybrid_search: The query parameters to configure hybrid search behaviors. - :vartype hybrid_search: ~azure.search.documents.models.HybridSearch - """ - - _validation = { - "semantic_max_wait_in_milliseconds": {"minimum": 700}, - } - - _attribute_map = { - "include_total_result_count": {"key": "count", "type": "bool"}, - "facets": {"key": "facets", "type": "[str]"}, - "filter": {"key": "filter", "type": "str"}, - "highlight_fields": {"key": "highlight", "type": "str"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "orderby", "type": "str"}, - "query_type": {"key": "queryType", "type": "str"}, - "scoring_statistics": {"key": "scoringStatistics", "type": "str"}, - "session_id": {"key": "sessionId", "type": "str"}, - "scoring_parameters": {"key": "scoringParameters", "type": "[str]"}, - "scoring_profile": {"key": "scoringProfile", "type": "str"}, - "debug": {"key": "debug", "type": "str"}, - "search_text": {"key": "search", "type": "str"}, - "search_fields": {"key": "searchFields", "type": "str"}, - "search_mode": {"key": "searchMode", "type": "str"}, - "query_language": {"key": "queryLanguage", "type": "str"}, - "speller": {"key": "speller", "type": "str"}, - "select": {"key": "select", "type": "str"}, - "skip": {"key": "skip", "type": "int"}, - "top": {"key": "top", "type": "int"}, - "semantic_configuration": {"key": "semanticConfiguration", "type": "str"}, - "semantic_error_handling": {"key": "semanticErrorHandling", "type": "str"}, - "semantic_max_wait_in_milliseconds": {"key": "semanticMaxWaitInMilliseconds", "type": "int"}, - "semantic_query": {"key": "semanticQuery", "type": "str"}, - "answers": {"key": "answers", "type": "str"}, - "captions": {"key": "captions", "type": "str"}, - "query_rewrites": {"key": "queryRewrites", "type": "str"}, - "semantic_fields": {"key": "semanticFields", "type": "str"}, - "vector_queries": {"key": "vectorQueries", "type": "[VectorQuery]"}, - "vector_filter_mode": {"key": "vectorFilterMode", "type": "str"}, - "hybrid_search": {"key": "hybridSearch", "type": "HybridSearch"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - include_total_result_count: Optional[bool] = None, - facets: Optional[list[str]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - highlight_fields: Optional[str] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[str] = None, - query_type: Optional[Union[str, "_models.QueryType"]] = None, - scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = None, - session_id: Optional[str] = None, - scoring_parameters: Optional[list[str]] = None, - scoring_profile: Optional[str] = None, - debug: Optional[Union[str, "_models.QueryDebugMode"]] = None, - search_text: Optional[str] = None, - search_fields: Optional[str] = None, - search_mode: Optional[Union[str, "_models.SearchMode"]] = None, - query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, - speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, - select: Optional[str] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - semantic_configuration: Optional[str] = None, - semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - semantic_query: Optional[str] = None, - answers: Optional[Union[str, "_models.QueryAnswerType"]] = None, - captions: Optional[Union[str, "_models.QueryCaptionType"]] = None, - query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, - semantic_fields: Optional[str] = None, - vector_queries: Optional[list["_models.VectorQuery"]] = None, - vector_filter_mode: Optional[Union[str, "_models.VectorFilterMode"]] = None, - hybrid_search: Optional["_models.HybridSearch"] = None, - **kwargs: Any - ) -> None: - """ - :keyword include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :paramtype include_total_result_count: bool - :keyword facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :paramtype facets: list[str] - :keyword filter: The OData $filter expression to apply to the search query. - :paramtype filter: str - :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. - :paramtype highlight_fields: str - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :paramtype order_by: str - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. Known - values are: "local", "global", and "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :paramtype session_id: str - :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :paramtype scoring_parameters: list[str] - :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :paramtype scoring_profile: str - :keyword debug: Enables a debugging tool that can be used to further explore your reranked - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. - :paramtype search_text: str - :keyword search_fields: The comma-separated list of field names to which to scope the full-text - search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the - field names of each fielded search expression take precedence over any field names listed in - this parameter. - :paramtype search_fields: str - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: A value that specifies the language of the search query. Known values - are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", - "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", - "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", - "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", - "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", - "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", - "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", - "te-in", and "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Known values are: "none" and "lexicon". - :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields - marked as retrievable in the schema are included. - :paramtype select: str - :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use skip due to this limitation, consider - using orderby on a totally-ordered key and filter with a range query instead. - :paramtype skip: int - :keyword top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :paramtype top: int - :keyword semantic_configuration: The name of a semantic configuration that will be used when - processing documents for queries of type semantic. - :paramtype semantic_configuration: str - :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount - of time it takes for semantic enrichment to finish processing before the request fails. - :paramtype semantic_max_wait_in_milliseconds: int - :keyword semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :paramtype semantic_query: str - :keyword answers: A value that specifies whether answers should be returned as part of the - search response. Known values are: "none" and "extractive". - :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType - :keyword captions: A value that specifies whether captions should be returned as part of the - search response. Known values are: "none" and "extractive". - :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType - :keyword query_rewrites: A value that specifies whether query rewrites should be generated to - augment the search query. Known values are: "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. - :paramtype semantic_fields: str - :keyword vector_queries: The query parameters for vector and hybrid search queries. - :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter' for new indexes. Known values are: - "postFilter", "preFilter", and "strictPostFilter". - :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - """ - super().__init__(**kwargs) - self.include_total_result_count = include_total_result_count - self.facets = facets - self.filter = filter - self.highlight_fields = highlight_fields - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.query_type = query_type - self.scoring_statistics = scoring_statistics - self.session_id = session_id - self.scoring_parameters = scoring_parameters - self.scoring_profile = scoring_profile - self.debug = debug - self.search_text = search_text - self.search_fields = search_fields - self.search_mode = search_mode - self.query_language = query_language - self.speller = speller - self.select = select - self.skip = skip - self.top = top - self.semantic_configuration = semantic_configuration - self.semantic_error_handling = semantic_error_handling - self.semantic_max_wait_in_milliseconds = semantic_max_wait_in_milliseconds - self.semantic_query = semantic_query - self.answers = answers - self.captions = captions - self.query_rewrites = query_rewrites - self.semantic_fields = semantic_fields - self.vector_queries = vector_queries - self.vector_filter_mode = vector_filter_mode - self.hybrid_search = hybrid_search - - -class SearchResult(_serialization.Model): - """Contains a document found by a search query, plus associated metadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar score: The relevance score of the document compared to other documents returned by the - query. Required. - :vartype score: float - :ivar reranker_score: The relevance score computed by the semantic ranker for the top search - results. Search results are sorted by the RerankerScore first and then by the Score. - RerankerScore is only returned for queries of type 'semantic'. - :vartype reranker_score: float - :ivar reranker_boosted_score: The relevance score computed by boosting the Reranker Score. - Search results are sorted by the RerankerScore/RerankerBoostedScore based on - useScoringProfileBoostedRanking in the Semantic Config. RerankerBoostedScore is only returned - for queries of type 'semantic'. - :vartype reranker_boosted_score: float - :ivar highlights: Text fragments from the document that indicate the matching search terms, - organized by each applicable field; null if hit highlighting was not enabled for the query. - :vartype highlights: dict[str, list[str]] - :ivar captions: Captions are the most representative passages from the document relatively to - the search query. They are often used as document summary. Captions are only returned for - queries of type 'semantic'. - :vartype captions: list[~azure.search.documents.models.QueryCaptionResult] - :ivar document_debug_info: Contains debugging information that can be used to further explore - your search results. - :vartype document_debug_info: ~azure.search.documents.models.DocumentDebugInfo - """ - - _validation = { - "score": {"required": True, "readonly": True}, - "reranker_score": {"readonly": True}, - "reranker_boosted_score": {"readonly": True}, - "highlights": {"readonly": True}, - "captions": {"readonly": True}, - "document_debug_info": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "score": {"key": "@search\\.score", "type": "float"}, - "reranker_score": {"key": "@search\\.rerankerScore", "type": "float"}, - "reranker_boosted_score": {"key": "@search\\.rerankerBoostedScore", "type": "float"}, - "highlights": {"key": "@search\\.highlights", "type": "{[str]}"}, - "captions": {"key": "@search\\.captions", "type": "[QueryCaptionResult]"}, - "document_debug_info": {"key": "@search\\.documentDebugInfo", "type": "DocumentDebugInfo"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.score: Optional[float] = None - self.reranker_score: Optional[float] = None - self.reranker_boosted_score: Optional[float] = None - self.highlights: Optional[dict[str, list[str]]] = None - self.captions: Optional[list["_models.QueryCaptionResult"]] = None - self.document_debug_info: Optional["_models.DocumentDebugInfo"] = None - - -class VectorThreshold(_serialization.Model): - """The threshold used for vector queries. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - SearchScoreThreshold, VectorSimilarityThreshold - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of threshold used to filter vector queries. Required. Known values are: - "vectorSimilarity" and "searchScore". - :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = {"kind": {"searchScore": "SearchScoreThreshold", "vectorSimilarity": "VectorSimilarityThreshold"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class SearchScoreThreshold(VectorThreshold): - """The results of the vector query will filter based on the '\\@search.score' value. Note this is - the @search.score returned as part of the search response. The threshold direction will be - chosen for higher @search.score. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of threshold used to filter vector queries. Required. Known values are: - "vectorSimilarity" and "searchScore". - :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind - :ivar value: The threshold will filter based on the '\\@search.score' value. Note this is the - @search.score returned as part of the search response. The threshold direction will be chosen - for higher @search.score. Required. - :vartype value: float - """ - - _validation = { - "kind": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, *, value: float, **kwargs: Any) -> None: - """ - :keyword value: The threshold will filter based on the '\\@search.score' value. Note this is the - @search.score returned as part of the search response. The threshold direction will be chosen - for higher @search.score. Required. - :paramtype value: float - """ - super().__init__(**kwargs) - self.kind: str = "searchScore" - self.value = value - - -class SemanticDebugInfo(_serialization.Model): - """SemanticDebugInfo. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar title_field: The title field that was sent to the semantic enrichment process, as well as - how it was used. - :vartype title_field: ~azure.search.documents.models.QueryResultDocumentSemanticField - :ivar content_fields: The content fields that were sent to the semantic enrichment process, as - well as how they were used. - :vartype content_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] - :ivar keyword_fields: The keyword fields that were sent to the semantic enrichment process, as - well as how they were used. - :vartype keyword_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] - :ivar reranker_input: The raw concatenated strings that were sent to the semantic enrichment - process. - :vartype reranker_input: ~azure.search.documents.models.QueryResultDocumentRerankerInput - """ - - _validation = { - "title_field": {"readonly": True}, - "content_fields": {"readonly": True}, - "keyword_fields": {"readonly": True}, - "reranker_input": {"readonly": True}, - } - - _attribute_map = { - "title_field": {"key": "titleField", "type": "QueryResultDocumentSemanticField"}, - "content_fields": {"key": "contentFields", "type": "[QueryResultDocumentSemanticField]"}, - "keyword_fields": {"key": "keywordFields", "type": "[QueryResultDocumentSemanticField]"}, - "reranker_input": {"key": "rerankerInput", "type": "QueryResultDocumentRerankerInput"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.title_field: Optional["_models.QueryResultDocumentSemanticField"] = None - self.content_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = None - self.keyword_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = None - self.reranker_input: Optional["_models.QueryResultDocumentRerankerInput"] = None - - -class SingleVectorFieldResult(_serialization.Model): - """A single vector field result. Both @search.score and vector similarity values are returned. - Vector similarity is related to @search.score by an equation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar search_score: The @search.score value that is calculated from the vector similarity - score. This is the score that's visible in a pure single-field single-vector query. - :vartype search_score: float - :ivar vector_similarity: The vector similarity score for this document. Note this is the - canonical definition of similarity metric, not the 'distance' version. For example, cosine - similarity instead of cosine distance. - :vartype vector_similarity: float - """ - - _validation = { - "search_score": {"readonly": True}, - "vector_similarity": {"readonly": True}, - } - - _attribute_map = { - "search_score": {"key": "searchScore", "type": "float"}, - "vector_similarity": {"key": "vectorSimilarity", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.search_score: Optional[float] = None - self.vector_similarity: Optional[float] = None - - -class SuggestDocumentsResult(_serialization.Model): - """Response containing suggestion query results from an index. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar results: The sequence of results returned by the query. Required. - :vartype results: list[~azure.search.documents.models.SuggestResult] - :ivar coverage: A value indicating the percentage of the index that was included in the query, - or null if minimumCoverage was not set in the request. - :vartype coverage: float - """ - - _validation = { - "results": {"required": True, "readonly": True}, - "coverage": {"readonly": True}, - } - - _attribute_map = { - "results": {"key": "value", "type": "[SuggestResult]"}, - "coverage": {"key": "@search\\.coverage", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.results: Optional[list["_models.SuggestResult"]] = None - self.coverage: Optional[float] = None - - -class SuggestOptions(_serialization.Model): - """Parameter group. - - :ivar filter: An OData expression that filters the documents considered for suggestions. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestions - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestions queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestions query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :vartype order_by: list[str] - :ivar search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :vartype search_fields: list[str] - :ivar select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :vartype select: list[str] - :ivar top: The number of suggestions to retrieve. The value must be a number between 1 and 100. - The default is 5. - :vartype top: int - """ - - _attribute_map = { - "filter": {"key": "$filter", "type": "str"}, - "use_fuzzy_matching": {"key": "UseFuzzyMatching", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "OrderBy", "type": "[str]"}, - "search_fields": {"key": "searchFields", "type": "[str]"}, - "select": {"key": "$select", "type": "[str]"}, - "top": {"key": "$top", "type": "int"}, - } - - def __init__( - self, - *, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - search_fields: Optional[list[str]] = None, - select: Optional[list[str]] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword filter: An OData expression that filters the documents considered for suggestions. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - suggestions query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy suggestions queries are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a suggestions query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :paramtype minimum_coverage: float - :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :paramtype order_by: list[str] - :keyword search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :paramtype search_fields: list[str] - :keyword select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :paramtype select: list[str] - :keyword top: The number of suggestions to retrieve. The value must be a number between 1 and - 100. The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.search_fields = search_fields - self.select = select - self.top = top - - -class SuggestRequest(_serialization.Model): - """Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors. - - All required parameters must be populated in order to send to server. - - :ivar filter: An OData expression that filters the documents considered for suggestions. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestion - query. Default is false. When set to true, the query will find suggestions even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestion searches are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestion query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: str - :ivar search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :vartype search_text: str - :ivar search_fields: The comma-separated list of field names to search for the specified search - text. Target fields must be included in the specified suggester. - :vartype search_fields: str - :ivar select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. - :vartype select: str - :ivar suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :vartype suggester_name: str - :ivar top: The number of suggestions to retrieve. This must be a value between 1 and 100. The - default is 5. - :vartype top: int - """ - - _validation = { - "search_text": {"required": True}, - "suggester_name": {"required": True}, - } - - _attribute_map = { - "filter": {"key": "filter", "type": "str"}, - "use_fuzzy_matching": {"key": "fuzzy", "type": "bool"}, - "highlight_post_tag": {"key": "highlightPostTag", "type": "str"}, - "highlight_pre_tag": {"key": "highlightPreTag", "type": "str"}, - "minimum_coverage": {"key": "minimumCoverage", "type": "float"}, - "order_by": {"key": "orderby", "type": "str"}, - "search_text": {"key": "search", "type": "str"}, - "search_fields": {"key": "searchFields", "type": "str"}, - "select": {"key": "select", "type": "str"}, - "suggester_name": {"key": "suggesterName", "type": "str"}, - "top": {"key": "top", "type": "int"}, - } - - def __init__( - self, - *, - search_text: str, - suggester_name: str, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[str] = None, - search_fields: Optional[str] = None, - select: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword filter: An OData expression that filters the documents considered for suggestions. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - suggestion query. Default is false. When set to true, the query will find suggestions even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are - slower and consume more resources. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a suggestion query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :paramtype order_by: str - :keyword search_text: The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. Required. - :paramtype search_text: str - :keyword search_fields: The comma-separated list of field names to search for the specified - search text. Target fields must be included in the specified suggester. - :paramtype search_fields: str - :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. - :paramtype select: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. - The default is 5. - :paramtype top: int - """ - super().__init__(**kwargs) - self.filter = filter - self.use_fuzzy_matching = use_fuzzy_matching - self.highlight_post_tag = highlight_post_tag - self.highlight_pre_tag = highlight_pre_tag - self.minimum_coverage = minimum_coverage - self.order_by = order_by - self.search_text = search_text - self.search_fields = search_fields - self.select = select - self.suggester_name = suggester_name - self.top = top - - -class SuggestResult(_serialization.Model): - """A result containing a document found by a suggestion query, plus associated metadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar text: The text of the suggestion result. Required. - :vartype text: str - """ - - _validation = { - "text": {"required": True, "readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "text": {"key": "@search\\.text", "type": "str"}, - } - - def __init__(self, *, additional_properties: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.text: Optional[str] = None - - -class TextResult(_serialization.Model): - """The BM25 or Classic score for the text portion of the query. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar search_score: The BM25 or Classic score for the text portion of the query. - :vartype search_score: float - """ - - _validation = { - "search_score": {"readonly": True}, - } - - _attribute_map = { - "search_score": {"key": "searchScore", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.search_score: Optional[float] = None - - -class VectorQuery(_serialization.Model): - """The query parameters for vector and hybrid search queries. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - VectorizableImageBinaryQuery, VectorizableImageUrlQuery, VectorizableTextQuery, VectorizedQuery - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :vartype k_nearest_neighbors: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k_nearest_neighbors": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - } - - _subtype_map = { - "kind": { - "imageBinary": "VectorizableImageBinaryQuery", - "imageUrl": "VectorizableImageUrlQuery", - "text": "VectorizableTextQuery", - "vector": "VectorizedQuery", - } - } - - def __init__( - self, - *, - k_nearest_neighbors: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :paramtype k_nearest_neighbors: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - self.k_nearest_neighbors = k_nearest_neighbors - self.fields = fields - self.exhaustive = exhaustive - self.oversampling = oversampling - self.weight = weight - self.threshold = threshold - self.filter_override = filter_override - self.per_document_vector_limit = per_document_vector_limit - - -class VectorizableImageBinaryQuery(VectorQuery): - """The query parameters to use for vector search when a base 64 encoded binary of an image that - needs to be vectorized is provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :vartype k_nearest_neighbors: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar base64_image: The base 64 encoded binary of an image to be vectorized to perform a vector - search query. - :vartype base64_image: str - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k_nearest_neighbors": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "base64_image": {"key": "base64Image", "type": "str"}, - } - - def __init__( - self, - *, - k_nearest_neighbors: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - base64_image: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :paramtype k_nearest_neighbors: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword base64_image: The base 64 encoded binary of an image to be vectorized to perform a - vector search query. - :paramtype base64_image: str - """ - super().__init__( - k_nearest_neighbors=k_nearest_neighbors, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "imageBinary" - self.base64_image = base64_image - - -class VectorizableImageUrlQuery(VectorQuery): - """The query parameters to use for vector search when an url that represents an image value that - needs to be vectorized is provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :vartype k_nearest_neighbors: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar url: The URL of an image to be vectorized to perform a vector search query. - :vartype url: str - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k_nearest_neighbors": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "url": {"key": "url", "type": "str"}, - } - - def __init__( - self, - *, - k_nearest_neighbors: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - url: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :paramtype k_nearest_neighbors: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword url: The URL of an image to be vectorized to perform a vector search query. - :paramtype url: str - """ - super().__init__( - k_nearest_neighbors=k_nearest_neighbors, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "imageUrl" - self.url = url - - -class VectorizableTextQuery(VectorQuery): - """The query parameters to use for vector search when a text value that needs to be vectorized is - provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :vartype k_nearest_neighbors: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar text: The text to be vectorized to perform a vector search query. Required. - :vartype text: str - :ivar query_rewrites: Can be configured to let a generative model rewrite the query before - sending it to be vectorized. Known values are: "none" and "generative". - :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - """ - - _validation = { - "kind": {"required": True}, - "text": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k_nearest_neighbors": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "text": {"key": "text", "type": "str"}, - "query_rewrites": {"key": "queryRewrites", "type": "str"}, - } - - def __init__( - self, - *, - text: str, - k_nearest_neighbors: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :paramtype k_nearest_neighbors: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword text: The text to be vectorized to perform a vector search query. Required. - :paramtype text: str - :keyword query_rewrites: Can be configured to let a generative model rewrite the query before - sending it to be vectorized. Known values are: "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - """ - super().__init__( - k_nearest_neighbors=k_nearest_neighbors, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "text" - self.text = text - self.query_rewrites = query_rewrites - - -class VectorizedQuery(VectorQuery): - """The query parameters to use for vector search when a raw vector value is provided. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of vector query being performed. Required. Known values are: "vector", - "text", "imageUrl", and "imageBinary". - :vartype kind: str or ~azure.search.documents.models.VectorQueryKind - :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :vartype k_nearest_neighbors: int - :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :vartype fields: str - :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :vartype exhaustive: bool - :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :vartype oversampling: float - :ivar weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :vartype weight: float - :ivar threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :vartype threshold: ~azure.search.documents.models.VectorThreshold - :ivar filter_override: The OData filter expression to apply to this specific vector query. If - no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :vartype filter_override: str - :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in - a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :vartype per_document_vector_limit: int - :ivar vector: The vector representation of a search query. Required. - :vartype vector: list[float] - """ - - _validation = { - "kind": {"required": True}, - "vector": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "k_nearest_neighbors": {"key": "k", "type": "int"}, - "fields": {"key": "fields", "type": "str"}, - "exhaustive": {"key": "exhaustive", "type": "bool"}, - "oversampling": {"key": "oversampling", "type": "float"}, - "weight": {"key": "weight", "type": "float"}, - "threshold": {"key": "threshold", "type": "VectorThreshold"}, - "filter_override": {"key": "filterOverride", "type": "str"}, - "per_document_vector_limit": {"key": "perDocumentVectorLimit", "type": "int"}, - "vector": {"key": "vector", "type": "[float]"}, - } - - def __init__( - self, - *, - vector: list[float], - k_nearest_neighbors: Optional[int] = None, - fields: Optional[str] = None, - exhaustive: Optional[bool] = None, - oversampling: Optional[float] = None, - weight: Optional[float] = None, - threshold: Optional["_models.VectorThreshold"] = None, - filter_override: Optional[str] = None, - per_document_vector_limit: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword k_nearest_neighbors: Number of nearest neighbors to return as top hits. - :paramtype k_nearest_neighbors: int - :keyword fields: Vector Fields of type Collection(Edm.Single) to be included in the vector - searched. - :paramtype fields: str - :keyword exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all - vectors within the vector index. Useful for scenarios where exact matches are critical, such as - determining ground truth values. - :paramtype exhaustive: bool - :keyword oversampling: Oversampling factor. Minimum value is 1. It overrides the - 'defaultOversampling' parameter configured in the index definition. It can be set only when - 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method - is used on the underlying vector field. - :paramtype oversampling: float - :keyword weight: Relative weight of the vector query when compared to other vector query and/or - the text query within the same search request. This value is used when combining the results of - multiple ranking lists produced by the different vector queries and/or the results retrieved - through the text query. The higher the weight, the higher the documents that matched that query - will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger - than zero. - :paramtype weight: float - :keyword threshold: The threshold used for vector queries. Note this can only be set if all - 'fields' use the same similarity metric. - :paramtype threshold: ~azure.search.documents.models.VectorThreshold - :keyword filter_override: The OData filter expression to apply to this specific vector query. - If no filter expression is defined at the vector level, the expression defined in the top level - filter parameter is used instead. - :paramtype filter_override: str - :keyword per_document_vector_limit: Controls how many vectors can be matched from each document - in a vector search query. Setting it to 1 ensures at most one vector per document is matched, - guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple - relevant vectors from the same document to be matched. Default is 0. - :paramtype per_document_vector_limit: int - :keyword vector: The vector representation of a search query. Required. - :paramtype vector: list[float] - """ - super().__init__( - k_nearest_neighbors=k_nearest_neighbors, - fields=fields, - exhaustive=exhaustive, - oversampling=oversampling, - weight=weight, - threshold=threshold, - filter_override=filter_override, - per_document_vector_limit=per_document_vector_limit, - **kwargs - ) - self.kind: str = "vector" - self.vector = vector - - -class VectorsDebugInfo(_serialization.Model): - """VectorsDebugInfo. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar subscores: The breakdown of subscores of the document prior to the chosen result set - fusion/combination method such as RRF. - :vartype subscores: ~azure.search.documents.models.QueryResultDocumentSubscores - """ - - _validation = { - "subscores": {"readonly": True}, - } - - _attribute_map = { - "subscores": {"key": "subscores", "type": "QueryResultDocumentSubscores"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.subscores: Optional["_models.QueryResultDocumentSubscores"] = None - - -class VectorSimilarityThreshold(VectorThreshold): - """The results of the vector query will be filtered based on the vector similarity metric. Note - this is the canonical definition of similarity metric, not the 'distance' version. The - threshold direction (larger or smaller) will be chosen automatically according to the metric - used by the field. - - All required parameters must be populated in order to send to server. - - :ivar kind: The kind of threshold used to filter vector queries. Required. Known values are: - "vectorSimilarity" and "searchScore". - :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind - :ivar value: The threshold will filter based on the similarity metric value. Note this is the - canonical definition of similarity metric, not the 'distance' version. The threshold direction - (larger or smaller) will be chosen automatically according to the metric used by the field. - Required. - :vartype value: float - """ - - _validation = { - "kind": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, *, value: float, **kwargs: Any) -> None: - """ - :keyword value: The threshold will filter based on the similarity metric value. Note this is - the canonical definition of similarity metric, not the 'distance' version. The threshold - direction (larger or smaller) will be chosen automatically according to the metric used by the - field. Required. - :paramtype value: float - """ - super().__init__(**kwargs) - self.kind: str = "vectorSimilarity" - self.value = value diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py deleted file mode 100644 index 64518595356a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_documents_operations.py +++ /dev/null @@ -1,1520 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchIndexClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_count_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/$count") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_search_get_request( - *, - search_text: Optional[str] = None, - include_total_result_count: Optional[bool] = None, - facets: Optional[list[str]] = None, - filter: Optional[str] = None, - highlight_fields: Optional[list[str]] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - query_type: Optional[Union[str, _models.QueryType]] = None, - scoring_parameters: Optional[list[str]] = None, - scoring_profile: Optional[str] = None, - search_fields: Optional[list[str]] = None, - search_mode: Optional[Union[str, _models.SearchMode]] = None, - scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, - session_id: Optional[str] = None, - select: Optional[list[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - x_ms_client_request_id: Optional[str] = None, - semantic_configuration: Optional[str] = None, - semantic_error_handling: Optional[Union[str, _models.SemanticErrorMode]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - answers: Optional[Union[str, _models.QueryAnswerType]] = None, - captions: Optional[Union[str, _models.QueryCaptionType]] = None, - semantic_query: Optional[str] = None, - query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, - debug: Optional[Union[str, _models.QueryDebugMode]] = None, - query_language: Optional[Union[str, _models.QueryLanguage]] = None, - speller: Optional[Union[str, _models.QuerySpellerType]] = None, - semantic_fields: Optional[list[str]] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs") - - # Construct parameters - if search_text is not None: - _params["search"] = _SERIALIZER.query("search_text", search_text, "str") - if include_total_result_count is not None: - _params["$count"] = _SERIALIZER.query("include_total_result_count", include_total_result_count, "bool") - if facets is not None: - _params["facet"] = [_SERIALIZER.query("facets", q, "str") if q is not None else "" for q in facets] - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if highlight_fields is not None: - _params["highlight"] = _SERIALIZER.query("highlight_fields", highlight_fields, "[str]", div=",") - if highlight_post_tag is not None: - _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") - if highlight_pre_tag is not None: - _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") - if minimum_coverage is not None: - _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") - if order_by is not None: - _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") - if query_type is not None: - _params["queryType"] = _SERIALIZER.query("query_type", query_type, "str") - if scoring_parameters is not None: - _params["scoringParameter"] = [ - _SERIALIZER.query("scoring_parameters", q, "str") if q is not None else "" for q in scoring_parameters - ] - if scoring_profile is not None: - _params["scoringProfile"] = _SERIALIZER.query("scoring_profile", scoring_profile, "str") - if search_fields is not None: - _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") - if search_mode is not None: - _params["searchMode"] = _SERIALIZER.query("search_mode", search_mode, "str") - if scoring_statistics is not None: - _params["scoringStatistics"] = _SERIALIZER.query("scoring_statistics", scoring_statistics, "str") - if session_id is not None: - _params["sessionId"] = _SERIALIZER.query("session_id", session_id, "str") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") - if skip is not None: - _params["$skip"] = _SERIALIZER.query("skip", skip, "int") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if semantic_configuration is not None: - _params["semanticConfiguration"] = _SERIALIZER.query("semantic_configuration", semantic_configuration, "str") - if semantic_error_handling is not None: - _params["semanticErrorHandling"] = _SERIALIZER.query("semantic_error_handling", semantic_error_handling, "str") - if semantic_max_wait_in_milliseconds is not None: - _params["semanticMaxWaitInMilliseconds"] = _SERIALIZER.query( - "semantic_max_wait_in_milliseconds", semantic_max_wait_in_milliseconds, "int", minimum=700 - ) - if answers is not None: - _params["answers"] = _SERIALIZER.query("answers", answers, "str") - if captions is not None: - _params["captions"] = _SERIALIZER.query("captions", captions, "str") - if semantic_query is not None: - _params["semanticQuery"] = _SERIALIZER.query("semantic_query", semantic_query, "str") - if query_rewrites is not None: - _params["queryRewrites"] = _SERIALIZER.query("query_rewrites", query_rewrites, "str") - if debug is not None: - _params["debug"] = _SERIALIZER.query("debug", debug, "str") - if query_language is not None: - _params["queryLanguage"] = _SERIALIZER.query("query_language", query_language, "str") - if speller is not None: - _params["speller"] = _SERIALIZER.query("speller", speller, "str") - if semantic_fields is not None: - _params["semanticFields"] = _SERIALIZER.query("semantic_fields", semantic_fields, "[str]", div=",") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_search_post_request( - *, - x_ms_client_request_id: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.post.search") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - key: str, - *, - selected_fields: Optional[list[str]] = None, - x_ms_client_request_id: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs('{key}')") - path_format_arguments = { - "key": _SERIALIZER.url("key", key, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if selected_fields is not None: - _params["$select"] = _SERIALIZER.query("selected_fields", selected_fields, "[str]", div=",") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_suggest_get_request( - *, - search_text: str, - suggester_name: str, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[list[str]] = None, - search_fields: Optional[list[str]] = None, - select: Optional[list[str]] = None, - top: Optional[int] = None, - x_ms_client_request_id: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.suggest") - - # Construct parameters - _params["search"] = _SERIALIZER.query("search_text", search_text, "str") - _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if use_fuzzy_matching is not None: - _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") - if highlight_post_tag is not None: - _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") - if highlight_pre_tag is not None: - _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") - if minimum_coverage is not None: - _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") - if order_by is not None: - _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") - if search_fields is not None: - _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_suggest_post_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.post.suggest") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_index_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.index") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_autocomplete_get_request( - *, - search_text: str, - suggester_name: str, - x_ms_client_request_id: Optional[str] = None, - autocomplete_mode: Optional[Union[str, _models.AutocompleteMode]] = None, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[list[str]] = None, - top: Optional[int] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.autocomplete") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["search"] = _SERIALIZER.query("search_text", search_text, "str") - _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") - if autocomplete_mode is not None: - _params["autocompleteMode"] = _SERIALIZER.query("autocomplete_mode", autocomplete_mode, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if use_fuzzy_matching is not None: - _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") - if highlight_post_tag is not None: - _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") - if highlight_pre_tag is not None: - _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") - if minimum_coverage is not None: - _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") - if search_fields is not None: - _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_autocomplete_post_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/docs/search.post.autocomplete") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class DocumentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`documents` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def count(self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any) -> int: - """Queries the number of documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Count-Documents - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: int or the result of cls(response) - :rtype: int - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[int] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_count_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("int", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def search_get( - self, - search_text: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - search_options: Optional[_models.SearchOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. Default value is None. - :type search_text: str - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param search_options: Parameter group. Default value is None. - :type search_options: ~azure.search.documents.models.SearchOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _include_total_result_count = None - _facets = None - _filter = None - _highlight_fields = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _query_type = None - _scoring_parameters = None - _scoring_profile = None - _search_fields = None - _search_mode = None - _scoring_statistics = None - _session_id = None - _select = None - _skip = None - _top = None - _x_ms_client_request_id = None - _semantic_configuration = None - _semantic_error_handling = None - _semantic_max_wait_in_milliseconds = None - _answers = None - _captions = None - _semantic_query = None - _query_rewrites = None - _debug = None - _query_language = None - _speller = None - _semantic_fields = None - if search_options is not None: - _answers = search_options.answers - _captions = search_options.captions - _debug = search_options.debug - _facets = search_options.facets - _filter = search_options.filter - _highlight_fields = search_options.highlight_fields - _highlight_post_tag = search_options.highlight_post_tag - _highlight_pre_tag = search_options.highlight_pre_tag - _include_total_result_count = search_options.include_total_result_count - _minimum_coverage = search_options.minimum_coverage - _order_by = search_options.order_by - _query_language = search_options.query_language - _query_rewrites = search_options.query_rewrites - _query_type = search_options.query_type - _scoring_parameters = search_options.scoring_parameters - _scoring_profile = search_options.scoring_profile - _scoring_statistics = search_options.scoring_statistics - _search_fields = search_options.search_fields - _search_mode = search_options.search_mode - _select = search_options.select - _semantic_configuration = search_options.semantic_configuration - _semantic_error_handling = search_options.semantic_error_handling - _semantic_fields = search_options.semantic_fields - _semantic_max_wait_in_milliseconds = search_options.semantic_max_wait_in_milliseconds - _semantic_query = search_options.semantic_query - _session_id = search_options.session_id - _skip = search_options.skip - _speller = search_options.speller - _top = search_options.top - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_search_get_request( - search_text=search_text, - include_total_result_count=_include_total_result_count, - facets=_facets, - filter=_filter, - highlight_fields=_highlight_fields, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - query_type=_query_type, - scoring_parameters=_scoring_parameters, - scoring_profile=_scoring_profile, - search_fields=_search_fields, - search_mode=_search_mode, - scoring_statistics=_scoring_statistics, - session_id=_session_id, - select=_select, - skip=_skip, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - semantic_configuration=_semantic_configuration, - semantic_error_handling=_semantic_error_handling, - semantic_max_wait_in_milliseconds=_semantic_max_wait_in_milliseconds, - answers=_answers, - captions=_captions, - semantic_query=_semantic_query, - query_rewrites=_query_rewrites, - debug=_debug, - query_language=_query_language, - speller=_speller, - semantic_fields=_semantic_fields, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def search_post( - self, - search_request: _models.SearchRequest, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: ~azure.search.documents.models.SearchRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def search_post( - self, - search_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Required. - :type search_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def search_post( - self, - search_request: Union[_models.SearchRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchDocumentsResult: - """Searches for documents in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Search-Documents - - :param search_request: The definition of the Search request. Is either a SearchRequest type or - a IO[bytes] type. Required. - :type search_request: ~azure.search.documents.models.SearchRequest or IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SearchDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(search_request, (IOBase, bytes)): - _content = search_request - else: - _json = self._serialize.body(search_request, "SearchRequest") - - _request = build_search_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get( - self, - key: str, - selected_fields: Optional[list[str]] = None, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> dict[str, Any]: - """Retrieves a document from the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/lookup-document - - :param key: The key of the document to retrieve. Required. - :type key: str - :param selected_fields: List of field names to retrieve for the document; Any field not - retrieved will be missing from the returned document. Default value is None. - :type selected_fields: list[str] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: dict mapping str to any or the result of cls(response) - :rtype: dict[str, any] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[dict[str, Any]] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - key=key, - selected_fields=selected_fields, - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("{object}", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def suggest_get( - self, - search_text: str, - suggester_name: str, - suggest_options: Optional[_models.SuggestOptions] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param suggest_options: Parameter group. Default value is None. - :type suggest_options: ~azure.search.documents.models.SuggestOptions - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _order_by = None - _search_fields = None - _select = None - _top = None - _x_ms_client_request_id = None - if suggest_options is not None: - _filter = suggest_options.filter - _highlight_post_tag = suggest_options.highlight_post_tag - _highlight_pre_tag = suggest_options.highlight_pre_tag - _minimum_coverage = suggest_options.minimum_coverage - _order_by = suggest_options.order_by - _search_fields = suggest_options.search_fields - _select = suggest_options.select - _top = suggest_options.top - _use_fuzzy_matching = suggest_options.use_fuzzy_matching - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_suggest_get_request( - search_text=search_text, - suggester_name=suggester_name, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - order_by=_order_by, - search_fields=_search_fields, - select=_select, - top=_top, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def suggest_post( - self, - suggest_request: _models.SuggestRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def suggest_post( - self, - suggest_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Required. - :type suggest_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def suggest_post( - self, - suggest_request: Union[_models.SuggestRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/suggestions - - :param suggest_request: The Suggest request. Is either a SuggestRequest type or a IO[bytes] - type. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: SuggestDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(suggest_request, (IOBase, bytes)): - _content = suggest_request - else: - _json = self._serialize.body(suggest_request, "SuggestRequest") - - _request = build_suggest_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SuggestDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def index( - self, - batch: _models.IndexBatch, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexBatch - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def index( - self, - batch: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Required. - :type batch: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def index( - self, - batch: Union[_models.IndexBatch, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.IndexDocumentsResult: - """Sends a batch of document write actions to the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents - - :param batch: The batch of index actions. Is either a IndexBatch type or a IO[bytes] type. - Required. - :type batch: ~azure.search.documents.models.IndexBatch or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: IndexDocumentsResult or the result of cls(response) - :rtype: ~azure.search.documents.models.IndexDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.IndexDocumentsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(batch, (IOBase, bytes)): - _content = batch - else: - _json = self._serialize.body(batch, "IndexBatch") - - _request = build_index_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 207]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("IndexDocumentsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def autocomplete_get( - self, - search_text: str, - suggester_name: str, - request_options: Optional[_models.RequestOptions] = None, - autocomplete_options: Optional[_models.AutocompleteOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param search_text: The incomplete term which should be auto-completed. Required. - :type search_text: str - :param suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :type suggester_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :param autocomplete_options: Parameter group. Default value is None. - :type autocomplete_options: ~azure.search.documents.models.AutocompleteOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - _autocomplete_mode = None - _filter = None - _use_fuzzy_matching = None - _highlight_post_tag = None - _highlight_pre_tag = None - _minimum_coverage = None - _search_fields = None - _top = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - if autocomplete_options is not None: - _autocomplete_mode = autocomplete_options.autocomplete_mode - _filter = autocomplete_options.filter - _highlight_post_tag = autocomplete_options.highlight_post_tag - _highlight_pre_tag = autocomplete_options.highlight_pre_tag - _minimum_coverage = autocomplete_options.minimum_coverage - _search_fields = autocomplete_options.search_fields - _top = autocomplete_options.top - _use_fuzzy_matching = autocomplete_options.use_fuzzy_matching - - _request = build_autocomplete_get_request( - search_text=search_text, - suggester_name=suggester_name, - x_ms_client_request_id=_x_ms_client_request_id, - autocomplete_mode=_autocomplete_mode, - filter=_filter, - use_fuzzy_matching=_use_fuzzy_matching, - highlight_post_tag=_highlight_post_tag, - highlight_pre_tag=_highlight_pre_tag, - minimum_coverage=_minimum_coverage, - search_fields=_search_fields, - top=_top, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def autocomplete_post( - self, - autocomplete_request: _models.AutocompleteRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def autocomplete_post( - self, - autocomplete_request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def autocomplete_post( - self, - autocomplete_request: Union[_models.AutocompleteRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/autocomplete - - :param autocomplete_request: The definition of the Autocomplete request. Is either a - AutocompleteRequest type or a IO[bytes] type. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.models.RequestOptions - :return: AutocompleteResult or the result of cls(response) - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AutocompleteResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(autocomplete_request, (IOBase, bytes)): - _content = autocomplete_request - else: - _json = self._serialize.body(autocomplete_request, "AutocompleteRequest") - - _request = build_autocomplete_post_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AutocompleteResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed b/sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py b/sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py deleted file mode 100644 index e57206ead1ad..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py +++ /dev/null @@ -1,21 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from typing import Optional, Dict, Any, MutableMapping - - -class HeadersMixin: - @property - def _headers(self) -> Dict[str, Any]: - if self._aad: # type: ignore - return {"Accept": self._ODATA_ACCEPT} # type: ignore - return {"api-key": self._credential.key, "Accept": self._ODATA_ACCEPT} # type: ignore - - def _merge_client_headers(self, headers: Optional[MutableMapping[str, str]]) -> MutableMapping[str, str]: - headers = headers or {} - combined = self._headers - combined.update(headers) - return combined diff --git a/sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py b/sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py deleted file mode 100644 index db107813fd63..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py +++ /dev/null @@ -1,145 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, List, Dict, Any, Tuple, cast -from threading import Lock - -from ._generated.models import IndexAction - - -def _flatten_args(args: Tuple[Union[List[Dict[Any, Any]], List[List[Dict[Any, Any]]]], ...]) -> List[Dict]: - if len(args) == 1 and isinstance(args[0], (list, tuple)): - return cast(List[Dict], args[0]) - return cast(List[Dict], args) - - -class IndexDocumentsBatch: - """Represent a batch of update operations for documents in an Azure - Search index. - - Index operations are performed in the order in which they are added - to the batch. - - """ - - def __init__(self) -> None: - self._actions: List[IndexAction] = [] - self._lock = Lock() - - def __repr__(self) -> str: - return "".format(len(self.actions))[:1024] - - def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to upload to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: Documents to upload to an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return self._extend_batch(_flatten_args(documents), "upload") - - def add_delete_actions(self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any) -> List[IndexAction]: - # pylint: disable=unused-argument - """Add documents to delete to the Azure search index. - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: Documents to delete from an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return self._extend_batch(_flatten_args(documents), "delete") - - def add_merge_actions(self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any) -> List[IndexAction]: - # pylint: disable=unused-argument - """Add documents to merge in to existing documents in the Azure search - index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - - :param documents: Documents to merge into an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return self._extend_batch(_flatten_args(documents), "merge") - - def add_merge_or_upload_actions( - self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any - ) -> List[IndexAction]: - # pylint: disable=unused-argument - """Add documents to merge in to existing documents in the Azure search - index, or upload if they do not yet exist. - - This action behaves like *merge* if a document with the given key - already exists in the index. If the document does not exist, it behaves - like *upload* with a new document. - - :param documents: Documents to merge or upload into an Azure search - index. May be a single list of documents, or documents as individual - parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return self._extend_batch(_flatten_args(documents), "mergeOrUpload") - - @property - def actions(self) -> List[IndexAction]: - """The list of currently index actions to index. - - :rtype: list[IndexAction] - """ - return list(self._actions) - - def dequeue_actions(self, **kwargs: Any) -> List[IndexAction]: # pylint: disable=unused-argument - """Get the list of currently configured index actions and clear it. - - :return: the current actions - :rtype: list[IndexAction] - """ - with self._lock: - result = list(self._actions) - self._actions = [] - return result - - def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction]], **kwargs: Any) -> None: - # pylint: disable=unused-argument - """Enqueue a list of index actions to index. - - :param new_actions: the actions to enqueue - :type new_actions: IndexAction or list[IndexAction] - """ - if isinstance(new_actions, IndexAction): - with self._lock: - self._actions.append(new_actions) - else: - with self._lock: - self._actions.extend(new_actions) - - def _extend_batch(self, documents: List[Dict], action_type: str) -> List[IndexAction]: - new_actions = [IndexAction(additional_properties=document, action_type=action_type) for document in documents] - with self._lock: - self._actions.extend(new_actions) - return new_actions diff --git a/sdk/search/azure-search-documents/azure/search/documents/_paging.py b/sdk/search/azure-search-documents/azure/search/documents/_paging.py deleted file mode 100644 index de431227e160..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_paging.py +++ /dev/null @@ -1,182 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import List, Optional, Dict, cast, Any, MutableMapping - -import base64 -import itertools -import json - -from azure.core.paging import ItemPaged, PageIterator, ReturnType -from ._generated.models import SearchRequest, SearchDocumentsResult, QueryAnswerResult, DebugInfo -from ._api_versions import DEFAULT_VERSION - - -def convert_search_result(result): - ret = result.additional_properties - ret["@search.score"] = result.score - ret["@search.reranker_score"] = result.reranker_score - ret["@search.highlights"] = result.highlights - ret["@search.captions"] = result.captions - ret["@search.document_debug_info"] = result.document_debug_info - ret["@search.reranker_boosted_score"] = result.reranker_boosted_score - return ret - - -def pack_continuation_token(response, api_version=DEFAULT_VERSION): - if response.next_page_parameters is not None: - token = { - "apiVersion": api_version, - "nextLink": response.next_link, - "nextPageParameters": response.next_page_parameters.serialize(), - } - return base64.b64encode(json.dumps(token).encode("utf-8")) - return None - - -def unpack_continuation_token(token): - unpacked_token = json.loads(base64.b64decode(token)) - next_link = unpacked_token["nextLink"] - next_page_parameters = unpacked_token["nextPageParameters"] - next_page_request = SearchRequest.deserialize(next_page_parameters) - return next_link, next_page_request - - -class SearchItemPaged(ItemPaged[ReturnType]): - """A pageable list of search results.""" - - def __init__(self, *args, **kwargs) -> None: - super(SearchItemPaged, self).__init__(*args, **kwargs) - self._first_page_iterator_instance: Optional[SearchPageIterator] = None - - def __next__(self) -> ReturnType: - if self._page_iterator is None: - first_iterator = self._first_iterator_instance() - self._page_iterator = itertools.chain.from_iterable(first_iterator) - return next(self._page_iterator) - - def _first_iterator_instance(self) -> "SearchPageIterator": - if self._first_page_iterator_instance is None: - self._first_page_iterator_instance = cast(SearchPageIterator, self.by_page()) - return self._first_page_iterator_instance - - def get_facets(self) -> Optional[Dict]: - """Return any facet results if faceting was requested. - - :return: facet results - :rtype: dict or None - """ - return cast(Dict, self._first_iterator_instance().get_facets()) - - def get_coverage(self) -> float: - """Return the coverage percentage, if `minimum_coverage` was - specificied for the query. - - :return: coverage percentage - :rtype: float - """ - return cast(float, self._first_iterator_instance().get_coverage()) - - def get_count(self) -> int: - """Return the count of results if `include_total_count` was - set for the query. - - :return: count of results - :rtype: int - """ - return cast(int, self._first_iterator_instance().get_count()) - - def get_answers(self) -> Optional[List[QueryAnswerResult]]: - """Return semantic answers. Only included if the semantic ranker is used - and answers are requested in the search query via the query_answer parameter. - - :return: answers - :rtype: list[~azure.search.documents.models.QueryAnswerResult] or None - """ - return cast(List[QueryAnswerResult], self._first_iterator_instance().get_answers()) - - def get_debug_info(self) -> DebugInfo: - """Return the debug information for the query. - - :return: the debug information for the query - :rtype: ~azure.search.documents.models.DebugInfo - """ - return cast(DebugInfo, self._first_iterator_instance().get_debug_info()) - - -# The pylint error silenced below seems spurious, as the inner wrapper does, in -# fact, become a method of the class when it is applied. -def _ensure_response(f): - # pylint:disable=protected-access - def wrapper(self, *args, **kw): - if self._current_page is None: - self._response = self._get_next(self.continuation_token) - self.continuation_token, self._current_page = self._extract_data(self._response) - return f(self, *args, **kw) - - return wrapper - - -class SearchPageIterator(PageIterator): - """An iterator over search results.""" - - def __init__(self, client, initial_query, kwargs, continuation_token=None) -> None: - super(SearchPageIterator, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token, - ) - self._client = client - self._initial_query = initial_query - self._kwargs = kwargs - self._facets: Optional[MutableMapping[str, List[MutableMapping[str, Any]]]] = None - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - - def _get_next_cb(self, continuation_token): - if continuation_token is None: - return self._client.documents.search_post(search_request=self._initial_query.request, **self._kwargs) - - _next_link, next_page_request = unpack_continuation_token(continuation_token) - - return self._client.documents.search_post(search_request=next_page_request, **self._kwargs) - - def _extract_data_cb(self, response): - continuation_token = pack_continuation_token(response, api_version=self._api_version) - results = [convert_search_result(r) for r in response.results] - return continuation_token, results - - @_ensure_response - def get_facets(self) -> Optional[MutableMapping[str, Any]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - facets = response.facets - if facets is not None and self._facets is None: - assert facets.items() is not None # Hint for mypy - self._facets = {k: [x.as_dict() for x in v] for k, v in facets.items()} - return self._facets - - @_ensure_response - def get_coverage(self) -> float: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(float, response.coverage) - - @_ensure_response - def get_count(self) -> int: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(int, response.count) - - @_ensure_response - def get_answers(self) -> Optional[List[QueryAnswerResult]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return response.answers - - @_ensure_response - def get_debug_info(self) -> DebugInfo: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(DebugInfo, response.debug_info) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_queries.py b/sdk/search/azure-search-documents/azure/search/documents/_queries.py deleted file mode 100644 index bc24fbe7db91..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_queries.py +++ /dev/null @@ -1,135 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Type, Union, List, cast -from ._generated.models import AutocompleteRequest, SearchRequest, SuggestRequest - - -class _QueryBase: - - _request_type: Union[Type[AutocompleteRequest], Type[SearchRequest], Type[SuggestRequest]] = cast( - Union[Type[AutocompleteRequest], Type[SearchRequest], Type[SuggestRequest]], - None, - ) - - def __init__(self, **kwargs) -> None: - self._request = self._request_type(**kwargs) # pylint:disable=not-callable - - def __repr__(self) -> str: - return "<{} [{}]>".format(self.__class__.__name__, self._request.search_text)[:1024] - - def filter(self, expression: str) -> None: - """Add a `filter` expression for the search results. - - :param expression: An ODate expression of for the query filter. - :type expression: str - """ - self._request.filter = expression - - @property - def request(self) -> Union[AutocompleteRequest, SearchRequest, SuggestRequest]: - """The service request for this operation. - - :return: The service request for this operation. - :rtype: AutocompleteRequest or SearchRequest or SuggestRequest - """ - return self._request - - -class AutocompleteQuery(_QueryBase): - """Represent an autocomplete query again an Azure Search index.""" - - _request_type = AutocompleteRequest - - __doc__ = AutocompleteRequest.__doc__ - - -class SearchQuery(_QueryBase): - """Represent a rich search query again an Azure Search index.""" - - _request_type = SearchRequest - - __doc__ = SearchRequest.__doc__ - - def order_by(self, *fields: Union[str, List[str]]) -> None: - """Update the `orderby` property for the search results. - - :param fields: A list of fields for the query result to be ordered by. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SearchRequest, self._request) - request.order_by = ",".join(selects) - - def select(self, *fields: Union[str, List[str]]) -> None: - """Update the `select` property for the search results. - - :param fields: A list of fields for the query result to return. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SearchRequest, self._request) - request.select = ",".join(selects) - - -class SuggestQuery(_QueryBase): - """Represent a search suggestion query again an Azure Search index.""" - - _request_type = SuggestRequest - - __doc__ = SuggestRequest.__doc__ - - def order_by(self, *fields: Union[str, List[str]]) -> None: - """Update the `orderby` property for the search results. - - :param fields: A list of fields for the query result to be ordered by. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SuggestRequest, self._request) - request.order_by = ",".join(selects) - - def select(self, *fields: Union[str, List[str]]) -> None: - """Update the `select` property for the search results. - - :param fields: A list of fields for the query result to return. - :type fields: str or list[str] - :raises ValueError: If no fields are provided. - """ - if not fields: - raise ValueError("At least one field must be provided") - - selects = [] - for field in fields: - if isinstance(field, list): - selects.append(",".join(field)) - else: - selects.append(field) - request = cast(SuggestRequest, self._request) - request.select = ",".join(selects) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_client.py b/sdk/search/azure-search-documents/azure/search/documents/_search_client.py deleted file mode 100644 index 432df9673d5b..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_client.py +++ /dev/null @@ -1,746 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import cast, List, Any, Union, Dict, Optional, MutableMapping - -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from ._api_versions import DEFAULT_VERSION -from ._generated import SearchIndexClient -from ._generated.models import ( - AutocompleteMode, - AutocompleteRequest, - IndexAction, - IndexBatch, - IndexingResult, - QueryAnswerType, - QueryCaptionType, - QueryLanguage, - QuerySpellerType, - QueryType, - SearchMode, - ScoringStatistics, - VectorFilterMode, - VectorQuery, - SemanticErrorMode, - QueryDebugMode, - QueryRewritesType, - SuggestRequest, - HybridSearch, -) -from ._search_documents_error import RequestEntityTooLargeError -from ._index_documents_batch import IndexDocumentsBatch -from ._paging import SearchItemPaged, SearchPageIterator -from ._queries import AutocompleteQuery, SearchQuery, SuggestQuery -from ._headers_mixin import HeadersMixin -from ._utils import get_authentication_policy, get_answer_query, get_rewrites_query -from ._version import SDK_MONIKER - - -class SearchClient(HeadersMixin): - """A client to interact with an existing Azure search index. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param index_name: The name of the index to connect to - :type index_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START create_search_client_with_key] - :end-before: [END create_search_client_with_key] - :language: python - :dedent: 4 - :caption: Creating the SearchClient with an API key. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: SearchIndexClient - - def __init__( - self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = endpoint - self._index_name = index_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __repr__(self) -> str: - return "".format(repr(self._endpoint), repr(self._index_name))[:1024] - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - @distributed_trace - def get_document_count(self, **kwargs: Any) -> int: - """Return the number of documents in the Azure search index. - - :return: The count of documents in the index - :rtype: int - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return int(self._client.documents.count(**kwargs)) - - @distributed_trace - def get_document(self, key: str, selected_fields: Optional[List[str]] = None, **kwargs: Any) -> Dict: - """Retrieve a document from the Azure search index by its key. - - :param key: The primary key value for the document to retrieve - :type key: str - :param selected_fields: an allow-list of fields to include in the results - :type selected_fields: list[str] - :return: The document as stored in the Azure search index - :rtype: dict - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_get_document.py - :start-after: [START get_document] - :end-before: [END get_document] - :language: python - :dedent: 4 - :caption: Get a specific document from the search index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.documents.get(key=key, selected_fields=selected_fields, **kwargs) - return cast(dict, result) - - @distributed_trace - def search( - self, - search_text: Optional[str] = None, - *, - include_total_count: Optional[bool] = None, - facets: Optional[List[str]] = None, - filter: Optional[str] = None, - highlight_fields: Optional[str] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - query_type: Optional[Union[str, QueryType]] = None, - scoring_parameters: Optional[List[str]] = None, - scoring_profile: Optional[str] = None, - semantic_query: Optional[str] = None, - search_fields: Optional[List[str]] = None, - search_mode: Optional[Union[str, SearchMode]] = None, - query_language: Optional[Union[str, QueryLanguage]] = None, - query_speller: Optional[Union[str, QuerySpellerType]] = None, - query_answer: Optional[Union[str, QueryAnswerType]] = None, - query_answer_count: Optional[int] = None, - query_answer_threshold: Optional[float] = None, - query_caption: Optional[Union[str, QueryCaptionType]] = None, - query_caption_highlight_enabled: Optional[bool] = None, - semantic_fields: Optional[List[str]] = None, - semantic_configuration_name: Optional[str] = None, - select: Optional[List[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - scoring_statistics: Optional[Union[str, ScoringStatistics]] = None, - session_id: Optional[str] = None, - vector_queries: Optional[List[VectorQuery]] = None, - vector_filter_mode: Optional[Union[str, VectorFilterMode]] = None, - semantic_error_mode: Optional[Union[str, SemanticErrorMode]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - query_rewrites: Optional[Union[str, QueryRewritesType]] = None, - query_rewrites_count: Optional[int] = None, - debug: Optional[Union[str, QueryDebugMode]] = None, - hybrid_search: Optional[HybridSearch] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs: Any - ) -> SearchItemPaged[Dict]: - # pylint:disable=too-many-locals, disable=redefined-builtin - """Search the Azure search index for documents. - - :param str search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. - :keyword bool include_total_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :keyword list[str] facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :keyword str filter: The OData $filter expression to apply to the search query. - :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is . - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is . - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: - 'simple', 'full', "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword list[str] scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :keyword str scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :keyword str semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :keyword list[str] search_fields: The list of field names to which to scope the full-text search. When - using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of - each fielded search expression take precedence over any field names listed in this parameter. - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Possible values include: 'any', 'all'. - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: The language of the search query. Possible values include: "none", "en-us", - "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", - "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", - "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", - "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", - "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", - "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", - "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Possible values include: "none", "lexicon". - :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword query_answer: This parameter is only valid if the query type is 'semantic'. If set, - the query returns answers extracted from key passages in the highest ranked documents. - Possible values include: "none", "extractive". - :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType - :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. Configures the number of answers returned. Default count is 1. - :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. - :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the - query returns captions extracted from key passages in the highest ranked documents. - Defaults to 'None'. Possible values include: "none", "extractive". - :paramtype query_caption: str or ~azure.search.documents.models.QueryCaptionType - :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when - query caption is set to 'extractive'. Determines whether highlighting is enabled. - Defaults to 'true'. - :keyword list[str] semantic_fields: The list of field names used for semantic search. - :keyword semantic_configuration_name: The name of the semantic configuration that will be used when - processing documents for queries of type semantic. - :paramtype semantic_configuration_name: str - :keyword list[str] select: The list of fields to retrieve. If unspecified, all fields marked as retrievable - in the schema are included. - :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use $skip due to this limitation, - consider using $orderby on a totally-ordered key and $filter with a range query instead. - :keyword int top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. - Possible values include: "local", "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword str session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :keyword semantic_error_mode: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :paramtype semantic_error_mode: str or ~azure.search.documents.models.SemanticErrorMode - :keyword int semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent - to a generate model which will produce 10 (default) rewrites to help increase the recall of the - request. The requested count can be configured by appending the pipe character ``|`` followed - by the ``count-`` option, such as ``generative|count-3``. Defaults to - ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword int query_rewrites_count: This parameter is only valid if the query rewrites type is 'generative'. - Configures the number of rewrites returned. Default count is 10. - :keyword debug: Enables a debugging tool that can be used to further explore your Semantic search - results. Known values are: "disabled", "speller", "semantic", and "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword vector_queries: The query parameters for vector and hybrid search queries. - :paramtype vector_queries: list[VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". - :paramtype vector_filter_mode: str or VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - :keyword x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype x_ms_query_source_authorization: str - :return: List of search results. - :rtype: SearchItemPaged[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_simple_query.py - :start-after: [START simple_query] - :end-before: [END simple_query] - :language: python - :dedent: 4 - :caption: Search on a simple text term. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_filter_query.py - :start-after: [START filter_query] - :end-before: [END filter_query] - :language: python - :dedent: 4 - :caption: Filter and sort search results. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_facet_query.py - :start-after: [START facet_query] - :end-before: [END facet_query] - :language: python - :dedent: 4 - :caption: Get search result facets. - """ - include_total_result_count = include_total_count - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - - answers = get_answer_query(query_answer, query_answer_count, query_answer_threshold) - - rewrites = get_rewrites_query(query_rewrites, query_rewrites_count) - - captions = ( - query_caption - if not query_caption_highlight_enabled - else "{}|highlight-{}".format(query_caption, query_caption_highlight_enabled) - ) - - semantic_configuration = semantic_configuration_name - - query = SearchQuery( - search_text=search_text, - include_total_result_count=include_total_result_count, - facets=facets, - filter=filter_arg, - highlight_fields=highlight_fields, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - query_type=query_type, - scoring_parameters=scoring_parameters, - scoring_profile=scoring_profile, - semantic_query=semantic_query, - search_fields=search_fields_str, - search_mode=search_mode, - query_language=query_language, - speller=query_speller, - answers=answers, - captions=captions, - semantic_fields=",".join(semantic_fields) if semantic_fields else None, - semantic_configuration=semantic_configuration, - select=select if isinstance(select, str) else None, - skip=skip, - top=top, - session_id=session_id, - scoring_statistics=scoring_statistics, - vector_queries=vector_queries, - vector_filter_mode=vector_filter_mode, - semantic_error_handling=semantic_error_mode, - semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, - query_rewrites=rewrites, - debug=debug, - hybrid_search=hybrid_search, - ) - if isinstance(select, list): - query.select(select) - - if isinstance(order_by, list): - query.order_by(order_by) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["x_ms_query_source_authorization"] = x_ms_query_source_authorization - kwargs["api_version"] = self._api_version - return SearchItemPaged(self._client, query, kwargs, page_iterator_class=SearchPageIterator) - - @distributed_trace - def suggest( - self, - search_text: str, - suggester_name: str, - *, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, - top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search suggestion results from the Azure search index. - - :param str search_text: Required. The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. - :param str suggester_name: Required. The name of the suggester as specified in the suggesters - collection that's part of the index definition. - :keyword str filter: An OData expression that filters the documents considered for suggestions. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestions - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestions queries are slower and - consume more resources. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestions query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :keyword list[str] search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :keyword list[str] select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :keyword int top: The number of suggestions to retrieve. The value must be a number between 1 and - 100. The default is 5. - - :return: List of suggestion results. - :rtype: list[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_suggestions.py - :start-after: [START suggest_query] - :end-before: [END suggest_query] - :language: python - :dedent: 4 - :caption: Get search suggestions. - """ - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = SuggestQuery( - search_text=search_text, - suggester_name=suggester_name, - filter=filter_arg, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - search_fields=search_fields_str, - select=select if isinstance(select, str) else None, - top=top, - ) - if isinstance(select, list): - query.select(select) - if isinstance(order_by, list): - query.order_by(order_by) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(SuggestRequest, query.request) - response = self._client.documents.suggest_post(suggest_request=request, **kwargs) - assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - @distributed_trace - def autocomplete( - self, - search_text: str, - suggester_name: str, - *, - mode: Optional[Union[str, AutocompleteMode]] = None, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[List[str]] = None, - top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search auto-completion results from the Azure search index. - - :param str search_text: The search text on which to base autocomplete results. - :param str suggester_name: The name of the suggester as specified in the suggesters - collection that's part of the index definition. - :keyword mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Possible values include: 'oneTerm', 'twoTerms', 'oneTermWithContext'. - :paramtype mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword str filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :return: List of auto-completion results. - :rtype: list[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_autocomplete.py - :start-after: [START autocomplete_query] - :end-before: [END autocomplete_query] - :language: python - :dedent: 4 - :caption: Get a auto-completions. - """ - autocomplete_mode = mode - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = AutocompleteQuery( - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter_arg, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields_str, - top=top, - ) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(AutocompleteRequest, query.request) - response = self._client.documents.autocomplete_post(autocomplete_request=request, **kwargs) - assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - # pylint:disable=client-method-missing-tracing-decorator - def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Upload documents to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: A list of documents to upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_crud_operations.py - :start-after: [START upload_document] - :end-before: [END upload_document] - :language: python - :dedent: 4 - :caption: Upload new documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator, delete-operation-wrong-return-type - def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Delete documents from the Azure search index - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: A list of documents to delete. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_crud_operations.py - :start-after: [START delete_document] - :end-before: [END delete_document] - :language: python - :dedent: 4 - :caption: Delete existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_delete_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator - def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - - :param documents: A list of documents to merge. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_crud_operations.py - :start-after: [START merge_document] - :end-before: [END merge_document] - :language: python - :dedent: 4 - :caption: Merge fields into existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_merge_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator - def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index, - or upload them if they do not yet exist. - - This action behaves like `merge_documents` if a document with the given - key already exists in the index. If the document does not exist, it - behaves like `upload_documents` with a new document. - - :param documents: A list of documents to merge or upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - """ - batch = IndexDocumentsBatch() - batch.add_merge_or_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - @distributed_trace - def index_documents(self, batch: IndexDocumentsBatch, **kwargs: Any) -> List[IndexingResult]: - """Specify a document operations to perform as a batch. - - :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: List of IndexingResult - :rtype: list[IndexingResult] - - :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. - """ - return self._index_documents_actions(actions=batch.actions, **kwargs) - - def _index_documents_actions(self, actions: List[IndexAction], **kwargs: Any) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) - try: - batch_response = self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) - except RequestEntityTooLargeError: - if len(actions) == 1: - raise - pos = round(len(actions) / 2) - batch_response_first_half = self._index_documents_actions(actions=actions[:pos], **kwargs) - if batch_response_first_half: - result_first_half = batch_response_first_half - else: - result_first_half = [] - batch_response_second_half = self._index_documents_actions(actions=actions[pos:], **kwargs) - if batch_response_second_half: - result_second_half = batch_response_second_half - else: - result_second_half = [] - result_first_half.extend(result_second_half) - return result_first_half - - def __enter__(self) -> "SearchClient": - self._client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args) -> None: - self._client.__exit__(*args) - - @distributed_trace - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> HttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py b/sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py deleted file mode 100644 index fdcec1b4f7b2..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_documents_error.py +++ /dev/null @@ -1,10 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -from azure.core.exceptions import HttpResponseError - - -class RequestEntityTooLargeError(HttpResponseError): - """An error response with status code 413 - Request Entity Too Large""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py b/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py deleted file mode 100644 index 394a3660bb53..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py +++ /dev/null @@ -1,359 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import cast, List, Any, Union, Dict -import time -import threading - -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from azure.core.exceptions import ServiceResponseTimeoutError -from ._utils import is_retryable_status_code, get_authentication_policy -from .indexes import SearchIndexClient as SearchServiceClient -from ._search_indexing_buffered_sender_base import SearchIndexingBufferedSenderBase -from ._generated import SearchIndexClient -from ._generated.models import IndexingResult, IndexBatch, IndexAction -from ._search_documents_error import RequestEntityTooLargeError -from ._index_documents_batch import IndexDocumentsBatch -from ._headers_mixin import HeadersMixin -from ._version import SDK_MONIKER - - -class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixin): - """A buffered sender for document indexing actions. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param index_name: The name of the index to connect to - :type index_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword int auto_flush_interval: how many max seconds if between 2 flushes. This only takes effect - when auto_flush is on. Default to 60 seconds. - :keyword int initial_batch_action_count: The initial number of actions to group into a batch when - tuning the behavior of the sender. The default value is 512. - :keyword int max_retries_per_action: The number of times to retry a failed document. The default value is 3. - :keyword callable on_new: If it is set, the client will call corresponding methods when there - is a new IndexAction added. This may be called from main thread or a worker thread. - :keyword callable on_progress: If it is set, the client will call corresponding methods when there - is a IndexAction succeeds. This may be called from main thread or a worker thread. - :keyword callable on_error: If it is set, the client will call corresponding methods when there - is a IndexAction fails. This may be called from main thread or a worker thread. - :keyword callable on_remove: If it is set, the client will call corresponding methods when there - is a IndexAction removed from the queue (succeeds or fails). This may be called from main - thread or a worker thread. - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _client: SearchIndexClient - - # pylint: disable=too-many-instance-attributes - - def __init__( - self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any - ) -> None: - super(SearchIndexingBufferedSender, self).__init__( - endpoint=endpoint, index_name=index_name, credential=credential, **kwargs - ) - self._index_documents_batch = IndexDocumentsBatch() - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self._reset_timer() - - def _cleanup(self, flush: bool = True) -> None: - """Clean up the client. - - :param bool flush: flush the actions queue before shutdown the client - Default to True. - """ - if flush: - self.flush() - if self._auto_flush: - self._timer.cancel() - - def __repr__(self) -> str: - return "".format( - repr(self._endpoint), repr(self._index_name) - )[:1024] - - @property - def actions(self) -> List[IndexAction]: - """The list of currently index actions in queue to index. - - :rtype: list[IndexAction] - """ - return self._index_documents_batch.actions - - @distributed_trace - def close(self, **kwargs) -> None: # pylint: disable=unused-argument - """Close the session. - - :return: None - :rtype: None - """ - self._cleanup(flush=True) - return self._client.close() - - @distributed_trace - def flush(self, timeout: int = 86400, **kwargs: Any) -> bool: # pylint:disable=unused-argument - """Flush the batch. - - :param int timeout: time out setting. Default is 86400s (one day) - :return: True if there are errors. Else False - :rtype: bool - :raises ~azure.core.exceptions.ServiceResponseTimeoutError: - """ - has_error = False - begin_time = int(time.time()) - while len(self.actions) > 0: - now = int(time.time()) - remaining = timeout - (now - begin_time) - if remaining < 0: - if self._on_error: - actions = self._index_documents_batch.dequeue_actions() - for action in actions: - self._on_error(action) - raise ServiceResponseTimeoutError("Service response time out") - result = self._process(timeout=remaining, raise_error=False) - if result: - has_error = True - return has_error - - def _process(self, timeout: int = 86400, **kwargs) -> bool: - raise_error = kwargs.pop("raise_error", True) - actions = self._index_documents_batch.dequeue_actions() - has_error = False - if not self._index_key: - try: - credential = cast(Union[AzureKeyCredential, TokenCredential], self._credential) - client = SearchServiceClient(self._endpoint, credential) - index_result = client.get_index(self._index_name) - if index_result: - for field in index_result.fields: - if field.key: - self._index_key = field.name - break - except Exception: # pylint: disable=broad-except - pass - - self._reset_timer() - - try: - results = self._index_documents_actions(actions=actions, timeout=timeout) - for result in results: - try: - assert self._index_key is not None # Hint for mypy - action = next( - x - for x in actions - if x.additional_properties and x.additional_properties.get(self._index_key) == result.key - ) - if result.succeeded: - self._callback_succeed(action) - elif is_retryable_status_code(result.status_code): - self._retry_action(action) - has_error = True - else: - self._callback_fail(action) - has_error = True - except StopIteration: - pass - return has_error - except Exception: # pylint: disable=broad-except - for action in actions: - self._retry_action(action) - if raise_error: - raise - return True - return has_error - - def _process_if_needed(self) -> bool: - """Every time when a new action is queued, this method - will be triggered. It checks the actions already queued and flushes them if: - 1. Auto_flush is on - 2. There are self._batch_action_count actions queued - :return: True if proces is needed, False otherwise - :rtype: bool - """ - if not self._auto_flush: - return False - - if len(self._index_documents_batch.actions) < self._batch_action_count: - return False - - return self._process(raise_error=False) - - def _reset_timer(self): - # pylint: disable=access-member-before-definition - try: - self._timer.cancel() - except AttributeError: - pass - self._timer = threading.Timer(self._auto_flush_interval, self._process) - if self._auto_flush: - self._timer.start() - - @distributed_trace - def upload_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument - """Queue upload documents actions. - - :param documents: A list of documents to upload. - :type documents: list[dict] - """ - actions = self._index_documents_batch.add_upload_actions(documents) - self._callback_new(actions) - self._process_if_needed() - - @distributed_trace - def delete_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument - """Queue delete documents actions - - :param documents: A list of documents to delete. - :type documents: list[dict] - """ - actions = self._index_documents_batch.add_delete_actions(documents) - self._callback_new(actions) - self._process_if_needed() - - @distributed_trace - def merge_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument - """Queue merge documents actions - - :param documents: A list of documents to merge. - :type documents: list[dict] - """ - actions = self._index_documents_batch.add_merge_actions(documents) - self._callback_new(actions) - self._process_if_needed() - - @distributed_trace - def merge_or_upload_documents(self, documents: List[Dict], **kwargs) -> None: - # pylint: disable=unused-argument - """Queue merge documents or upload documents actions - - :param documents: A list of documents to merge or upload. - :type documents: list[dict] - """ - actions = self._index_documents_batch.add_merge_or_upload_actions(documents) - self._callback_new(actions) - self._process_if_needed() - - @distributed_trace - def index_documents(self, batch: IndexDocumentsBatch, **kwargs) -> List[IndexingResult]: - """Specify a document operations to perform as a batch. - - :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: Indexing result of each action in the batch. - :rtype: list[IndexingResult] - - :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. - """ - return self._index_documents_actions(actions=batch.actions, **kwargs) - - def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - - timeout = kwargs.pop("timeout", 86400) - begin_time = int(time.time()) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) - try: - batch_response = self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) - except RequestEntityTooLargeError as ex: - if len(actions) == 1: - raise - pos = round(len(actions) / 2) - if pos < self._batch_action_count: - self._index_documents_batch.enqueue_actions(actions) - now = int(time.time()) - remaining = timeout - (now - begin_time) - if remaining < 0: - raise ServiceResponseTimeoutError("Service response time out") from ex - batch_response_first_half = self._index_documents_actions( - actions=actions[:pos], timeout=remaining, **kwargs - ) - if len(batch_response_first_half) > 0: - result_first_half = batch_response_first_half - else: - result_first_half = [] - now = int(time.time()) - remaining = timeout - (now - begin_time) - if remaining < 0: - raise ServiceResponseTimeoutError("Service response time out") from ex - batch_response_second_half = self._index_documents_actions( - actions=actions[pos:], timeout=remaining, **kwargs - ) - if len(batch_response_second_half) > 0: - result_second_half = batch_response_second_half - else: - result_second_half = [] - result_first_half.extend(result_second_half) - return result_first_half - - def __enter__(self) -> "SearchIndexingBufferedSender": - self._client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args) -> None: - self.close() - self._client.__exit__(*args) - - def _retry_action(self, action: IndexAction) -> None: - if not self._index_key: - self._callback_fail(action) - return - key = cast(str, action.additional_properties.get(self._index_key) if action.additional_properties else "") - counter = self._retry_counter.get(key) - if not counter: - # first time that fails - self._retry_counter[key] = 1 - self._index_documents_batch.enqueue_actions(action) - elif counter < self._max_retries_per_action - 1: - # not reach retry limit yet - self._retry_counter[key] = counter + 1 - self._index_documents_batch.enqueue_actions(action) - else: - self._callback_fail(action) - - def _callback_succeed(self, action: IndexAction) -> None: - if self._on_remove: - self._on_remove(action) - if self._on_progress: - self._on_progress(action) - - def _callback_fail(self, action: IndexAction) -> None: - if self._on_remove: - self._on_remove(action) - if self._on_error: - self._on_error(action) - - def _callback_new(self, actions: List[IndexAction]) -> None: - if self._on_new: - for action in actions: - self._on_new(action) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py b/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py deleted file mode 100644 index 38fcdfbcd4a1..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender_base.py +++ /dev/null @@ -1,51 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -# pylint: disable=too-few-public-methods, too-many-instance-attributes -from typing import Any, Union, Dict, Optional - -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.credentials_async import AsyncTokenCredential -from ._api_versions import DEFAULT_VERSION -from ._headers_mixin import HeadersMixin - - -class SearchIndexingBufferedSenderBase(HeadersMixin): - """Base of search indexing buffered sender""" - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _DEFAULT_AUTO_FLUSH_INTERVAL = 60 - _DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512 - _DEFAULT_MAX_RETRIES = 3 - - def __init__( - self, - endpoint: str, - index_name: str, - credential: Union[AzureKeyCredential, TokenCredential, AsyncTokenCredential], - *, - auto_flush: bool = True, - initial_batch_action_count: int = _DEFAULT_INITIAL_BATCH_ACTION_COUNT, - auto_flush_interval: int = _DEFAULT_AUTO_FLUSH_INTERVAL, - max_retries_per_action: int = _DEFAULT_MAX_RETRIES, - **kwargs: Any - ) -> None: - - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._auto_flush = auto_flush - self._batch_action_count = initial_batch_action_count - self._auto_flush_interval = auto_flush_interval - if self._auto_flush_interval <= 0: - raise ValueError("auto_flush_interval must be a positive number.") - self._max_retries_per_action = max_retries_per_action - self._endpoint = endpoint - self._index_name = index_name - self._index_key: Optional[str] = None - self._credential = credential - self._on_new = kwargs.pop("on_new", None) - self._on_progress = kwargs.pop("on_progress", None) - self._on_error = kwargs.pop("on_error", None) - self._on_remove = kwargs.pop("on_remove", None) - self._retry_counter: Dict[str, int] = {} diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils.py b/sdk/search/azure-search-documents/azure/search/documents/_utils.py deleted file mode 100644 index 5b912120c1ed..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/_utils.py +++ /dev/null @@ -1,81 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Optional, Union -from azure.core.pipeline.policies import ( - BearerTokenCredentialPolicy, - AsyncBearerTokenCredentialPolicy, -) -from ._generated.models import QueryAnswerType, QueryRewritesType - -DEFAULT_AUDIENCE = "https://search.azure.com" - - -def get_answer_query( - query_answer: Optional[Union[str, QueryAnswerType]] = None, - query_answer_count: Optional[int] = None, - query_answer_threshold: Optional[float] = None, -) -> Optional[Union[str, QueryAnswerType]]: - answers = query_answer - separator = "|" - if query_answer_count: - answers = f"{answers}{separator}count-{query_answer_count}" - separator = "," - if query_answer_threshold: - answers = f"{answers}{separator}threshold-{query_answer_threshold}" - return answers - - -def get_rewrites_query( - query_rewrites: Optional[Union[str, QueryRewritesType]] = None, query_rewrites_count: Optional[int] = None -) -> Optional[Union[str, QueryRewritesType]]: - rewrites = query_rewrites - separator = "|" - if query_rewrites_count: - rewrites = f"{rewrites}{separator}count-{query_rewrites_count}" - return rewrites - - -def is_retryable_status_code(status_code: Optional[int]) -> bool: - if not status_code: - return False - return status_code in [422, 409, 503] - - -def get_authentication_policy(credential, *, is_async: bool = False, **kwargs): - audience = kwargs.get("audience", None) - if not audience: - audience = DEFAULT_AUDIENCE - scope = audience.rstrip("/") + "/.default" - _policy = BearerTokenCredentialPolicy if not is_async else AsyncBearerTokenCredentialPolicy - authentication_policy = _policy(credential, scope) - return authentication_policy - - -def odata(statement: str, **kwargs: Any) -> str: - """Escape an OData query string. - - The statement to prepare should include fields to substitute given inside - braces, e.g. `{somevar}` and then pass the corresponding value as a keyword - argument, e.g. `somevar=10`. - - :param statement: An OData query string to prepare - :type statement: str - :return: The prepared OData query string - :rtype: str - - .. admonition:: Example: - - >>> odata("name eq {name} and age eq {age}", name="O'Neil", age=37) - "name eq 'O''Neil' and age eq 37" - - - """ - for key, value in kwargs.items(): - if isinstance(value, str): - value = value.replace("'", "''") - if f"'{{{key}}}'" not in statement: - kwargs[key] = f"'{value}'" - return statement.format(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/__init__.py similarity index 52% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_utils/__init__.py index f986b371549e..8026245c2abc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/__init__.py @@ -1,4 +1,6 @@ # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/model_base.py @@ -0,0 +1,1237 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + return getattr(self._type, "args", [None])[0] + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + item = obj.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + return _deserialize(self._type, _serialize(item, self._format), rf=self) + + def __set__(self, obj: Model, value) -> None: + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/serialization.py similarity index 99% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/serialization.py rename to sdk/search/azure-search-documents/azure/search/documents/_utils/serialization.py index 003e1c89fb35..45a3e44e45cb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/serialization.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/serialization.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -785,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/search/azure-search-documents/azure/search/documents/_validation.py b/sdk/search/azure-search-documents/azure/search/documents/_validation.py new file mode 100644 index 000000000000..f5af3a4eb8a2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_validation.py @@ -0,0 +1,66 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools + + +def api_version_validation(**kwargs): + params_added_on = kwargs.pop("params_added_on", {}) + method_added_on = kwargs.pop("method_added_on", "") + api_versions_list = kwargs.pop("api_versions_list", []) + + def _index_with_default(value: str, default: int = -1) -> int: + """Get the index of value in lst, or return default if not found. + + :param value: The value to search for in the api_versions_list. + :type value: str + :param default: The default value to return if the value is not found. + :type default: int + :return: The index of the value in the list, or the default value if not found. + :rtype: int + """ + try: + return api_versions_list.index(value) + except ValueError: + return default + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + # this assumes the client has an _api_version attribute + client = args[0] + client_api_version = client._config.api_version # pylint: disable=protected-access + except AttributeError: + return func(*args, **kwargs) + + if _index_with_default(method_added_on) > _index_with_default(client_api_version): + raise ValueError( + f"'{func.__name__}' is not available in API version " + f"{client_api_version}. Pass service API version {method_added_on} or newer to your client." + ) + + unsupported = { + parameter: api_version + for api_version, parameters in params_added_on.items() + for parameter in parameters + if parameter in kwargs and _index_with_default(api_version) > _index_with_default(client_api_version) + } + if unsupported: + raise ValueError( + "".join( + [ + f"'{param}' is not available in API version {client_api_version}. " + f"Use service API version {version} or newer.\n" + for param, version in unsupported.items() + ] + ) + ) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/sdk/search/azure-search-documents/azure/search/documents/_version.py b/sdk/search/azure-search-documents/azure/search/documents/_version.py index ba5c5be36f25..80c9294bc018 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_version.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_version.py @@ -1,8 +1,9 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- -VERSION = "11.7.0b2" # type: str - -SDK_MONIKER = "search-documents/{}".format(VERSION) # type: str +VERSION = "11.7.0b2" diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/agent/__init__.py deleted file mode 100644 index e6760b0b795a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from ._agent_client import KnowledgeAgentRetrievalClient - -__all__ = ("KnowledgeAgentRetrievalClient",) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py deleted file mode 100644 index f53ab27ca7bc..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py +++ /dev/null @@ -1,97 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Union, Optional, IO - -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from .._api_versions import DEFAULT_VERSION -from ._generated import KnowledgeAgentRetrievalClient as _KnowledgeAgentRetrievalClient -from ._generated.models import ( - KnowledgeAgentRetrievalRequest, - RequestOptions, - KnowledgeAgentRetrievalResponse, -) -from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy -from .._version import SDK_MONIKER - - -class KnowledgeAgentRetrievalClient(HeadersMixin): - """A client that can be used to query an agent. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: _KnowledgeAgentRetrievalClient - - def __init__( - self, endpoint: str, agent_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = endpoint - self._agent_name = agent_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _KnowledgeAgentRetrievalClient( - endpoint=endpoint, - agent_name=agent_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = _KnowledgeAgentRetrievalClient( - endpoint=endpoint, - agent_name=agent_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self.knowledge_retrieval = self._client.knowledge_retrieval - - def __repr__(self) -> str: - return "".format( - repr(self._endpoint), repr(self._agent_name) - )[:1024] - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - @distributed_trace - def retrieve( - self, - retrieval_request: Union[KnowledgeAgentRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[RequestOptions] = None, - **kwargs: Any - ) -> KnowledgeAgentRetrievalResponse: - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return self._client.knowledge_retrieval.retrieve( - retrieval_request=retrieval_request, - x_ms_query_source_authorization=x_ms_query_source_authorization, - request_options=request_options, - **kwargs - ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_configuration.py deleted file mode 100644 index 2c38780be15c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class KnowledgeAgentRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for KnowledgeAgentRetrievalClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param agent_name: The name of the agent. Required. - :type agent_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, agent_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if agent_name is None: - raise ValueError("Parameter 'agent_name' must not be None.") - - self.endpoint = endpoint - self.agent_name = agent_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "knowledgeagentretrievalclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/__init__.py deleted file mode 100644 index 79e8ad096465..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_agent_retrieval_client import KnowledgeAgentRetrievalClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeAgentRetrievalClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_configuration.py deleted file mode 100644 index 4891889e5941..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class KnowledgeAgentRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for KnowledgeAgentRetrievalClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :param agent_name: The name of the agent. Required. - :type agent_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, agent_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if agent_name is None: - raise ValueError("Parameter 'agent_name' must not be None.") - - self.endpoint = endpoint - self.agent_name = agent_name - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "knowledgeagentretrievalclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/_knowledge_retrieval_operations.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/_knowledge_retrieval_operations.py deleted file mode 100644 index adb4b09ccb69..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/_knowledge_retrieval_operations.py +++ /dev/null @@ -1,193 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._knowledge_retrieval_operations import build_retrieve_request -from .._configuration import KnowledgeAgentRetrievalClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class KnowledgeRetrievalOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.agent.aio.KnowledgeAgentRetrievalClient`'s - :attr:`knowledge_retrieval` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: KnowledgeAgentRetrievalClientConfiguration = ( - input_args.pop(0) if input_args else kwargs.pop("config") - ) - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def retrieve( - self, - retrieval_request: _models.KnowledgeAgentRetrievalRequest, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgentRetrievalResponse: - """KnowledgeAgent retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Required. - :type retrieval_request: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.agent.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgentRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def retrieve( - self, - retrieval_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgentRetrievalResponse: - """KnowledgeAgent retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Required. - :type retrieval_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.agent.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgentRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def retrieve( - self, - retrieval_request: Union[_models.KnowledgeAgentRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeAgentRetrievalResponse: - """KnowledgeAgent retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Is either a - KnowledgeAgentRetrievalRequest type or a IO[bytes] type. Required. - :type retrieval_request: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalRequest or - IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.agent.models.RequestOptions - :return: KnowledgeAgentRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeAgentRetrievalResponse] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieval_request, (IOBase, bytes)): - _content = retrieval_request - else: - _json = self._serialize.body(retrieval_request, "KnowledgeAgentRetrievalRequest") - - _request = build_retrieve_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "agentName": self._serialize.url("self._config.agent_name", self._config.agent_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgentRetrievalResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/__init__.py deleted file mode 100644 index 39e57d0fa7c6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - KnowledgeAgentActivityRecord, - KnowledgeAgentAzureBlobActivityArguments, - KnowledgeAgentAzureBlobActivityRecord, - KnowledgeAgentAzureBlobReference, - KnowledgeAgentMessage, - KnowledgeAgentMessageContent, - KnowledgeAgentMessageImageContent, - KnowledgeAgentMessageImageContentImage, - KnowledgeAgentMessageTextContent, - KnowledgeAgentModelAnswerSynthesisActivityRecord, - KnowledgeAgentModelQueryPlanningActivityRecord, - KnowledgeAgentReference, - KnowledgeAgentRetrievalActivityRecord, - KnowledgeAgentRetrievalRequest, - KnowledgeAgentRetrievalResponse, - KnowledgeAgentSearchIndexActivityArguments, - KnowledgeAgentSearchIndexActivityRecord, - KnowledgeAgentSearchIndexReference, - KnowledgeAgentSemanticRerankerActivityRecord, - KnowledgeSourceParams, - RequestOptions, - SearchIndexKnowledgeSourceParams, -) - -from ._knowledge_agent_retrieval_client_enums import ( # type: ignore - KnowledgeAgentMessageContentType, - KnowledgeSourceKind, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "KnowledgeAgentActivityRecord", - "KnowledgeAgentAzureBlobActivityArguments", - "KnowledgeAgentAzureBlobActivityRecord", - "KnowledgeAgentAzureBlobReference", - "KnowledgeAgentMessage", - "KnowledgeAgentMessageContent", - "KnowledgeAgentMessageImageContent", - "KnowledgeAgentMessageImageContentImage", - "KnowledgeAgentMessageTextContent", - "KnowledgeAgentModelAnswerSynthesisActivityRecord", - "KnowledgeAgentModelQueryPlanningActivityRecord", - "KnowledgeAgentReference", - "KnowledgeAgentRetrievalActivityRecord", - "KnowledgeAgentRetrievalRequest", - "KnowledgeAgentRetrievalResponse", - "KnowledgeAgentSearchIndexActivityArguments", - "KnowledgeAgentSearchIndexActivityRecord", - "KnowledgeAgentSearchIndexReference", - "KnowledgeAgentSemanticRerankerActivityRecord", - "KnowledgeSourceParams", - "RequestOptions", - "SearchIndexKnowledgeSourceParams", - "KnowledgeAgentMessageContentType", - "KnowledgeSourceKind", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_knowledge_agent_retrieval_client_enums.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_knowledge_agent_retrieval_client_enums.py deleted file mode 100644 index ceabcf4a87b1..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_knowledge_agent_retrieval_client_enums.py +++ /dev/null @@ -1,26 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class KnowledgeAgentMessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of message content.""" - - TEXT = "text" - """Text message content kind.""" - IMAGE = "image" - """Image message content kind.""" - - -class KnowledgeSourceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The kind of the knowledge source.""" - - SEARCH_INDEX = "searchIndex" - """A knowledge source that reads data from a Search Index.""" - AZURE_BLOB = "azureBlob" - """A knowledge source that read and ingest data from Azure Blob Storage to a Search Index.""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_models_py3.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_models_py3.py deleted file mode 100644 index 8d63f3d827f2..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_models_py3.py +++ /dev/null @@ -1,1112 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Optional, TYPE_CHECKING, MutableMapping - -from .._utils import serialization as _serialization - -JSON = MutableMapping[str, Any] - -if TYPE_CHECKING: - from .. import models as _models - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.agent.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.search.documents.agent.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.search.documents.agent.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.search.documents.agent.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class KnowledgeAgentActivityRecord(_serialization.Model): - """Base type for activity records. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeAgentRetrievalActivityRecord, KnowledgeAgentModelAnswerSynthesisActivityRecord, - KnowledgeAgentModelQueryPlanningActivityRecord, KnowledgeAgentSemanticRerankerActivityRecord - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - } - - _subtype_map = { - "type": { - "KnowledgeAgentRetrievalActivityRecord": "KnowledgeAgentRetrievalActivityRecord", - "modelAnswerSynthesis": "KnowledgeAgentModelAnswerSynthesisActivityRecord", - "modelQueryPlanning": "KnowledgeAgentModelQueryPlanningActivityRecord", - "semanticReranker": "KnowledgeAgentSemanticRerankerActivityRecord", - } - } - - def __init__( - self, *, id: int, elapsed_ms: Optional[int] = None, **kwargs: Any # pylint: disable=redefined-builtin - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - """ - super().__init__(**kwargs) - self.id = id - self.type: Optional[str] = None - self.elapsed_ms = elapsed_ms - - -class KnowledgeAgentAzureBlobActivityArguments(_serialization.Model): - """Represents the arguments the azure blob retrieval activity was run with. - - :ivar search: The search string used to query blob contents. - :vartype search: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - } - - def __init__(self, *, search: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword search: The search string used to query blob contents. - :paramtype search: str - """ - super().__init__(**kwargs) - self.search = search - - -class KnowledgeAgentRetrievalActivityRecord(KnowledgeAgentActivityRecord): - """Represents a retrieval activity record. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeAgentAzureBlobActivityRecord, KnowledgeAgentSearchIndexActivityRecord - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - } - - _subtype_map = { - "type": { - "azureBlob": "KnowledgeAgentAzureBlobActivityRecord", - "searchIndex": "KnowledgeAgentSearchIndexActivityRecord", - } - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, **kwargs) - self.type: str = "KnowledgeAgentRetrievalActivityRecord" - self.knowledge_source_name = knowledge_source_name - self.query_time = query_time - self.count = count - - -class KnowledgeAgentAzureBlobActivityRecord(KnowledgeAgentRetrievalActivityRecord): - """Represents a azure blob retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar azure_blob_arguments: The azure blob arguments for the retrieval activity. - :vartype azure_blob_arguments: - ~azure.search.documents.agent.models.KnowledgeAgentAzureBlobActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "azure_blob_arguments": {"key": "azureBlobArguments", "type": "KnowledgeAgentAzureBlobActivityArguments"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - azure_blob_arguments: Optional["_models.KnowledgeAgentAzureBlobActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword azure_blob_arguments: The azure blob arguments for the retrieval activity. - :paramtype azure_blob_arguments: - ~azure.search.documents.agent.models.KnowledgeAgentAzureBlobActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "azureBlob" - self.azure_blob_arguments = azure_blob_arguments - - -class KnowledgeAgentReference(_serialization.Model): - """Base type for references. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeAgentAzureBlobReference, KnowledgeAgentSearchIndexReference - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - } - - _subtype_map = { - "type": {"azureBlob": "KnowledgeAgentAzureBlobReference", "searchIndex": "KnowledgeAgentSearchIndexReference"} - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.id = id - self.activity_source = activity_source - self.source_data = source_data - self.reranker_score = reranker_score - - -class KnowledgeAgentAzureBlobReference(KnowledgeAgentReference): - """Represents an Azure Blob Storage document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar blob_url: The blob URL for the reference. - :vartype blob_url: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "blob_url": {"key": "blobUrl", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - blob_url: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword blob_url: The blob URL for the reference. - :paramtype blob_url: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "azureBlob" - self.blob_url = blob_url - - -class KnowledgeAgentMessage(_serialization.Model): - """The natural language message style object. - - All required parameters must be populated in order to send to server. - - :ivar role: The role of the tool response. - :vartype role: str - :ivar content: Required. - :vartype content: list[~azure.search.documents.agent.models.KnowledgeAgentMessageContent] - """ - - _validation = { - "content": {"required": True}, - } - - _attribute_map = { - "role": {"key": "role", "type": "str"}, - "content": {"key": "content", "type": "[KnowledgeAgentMessageContent]"}, - } - - def __init__( - self, *, content: list["_models.KnowledgeAgentMessageContent"], role: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword role: The role of the tool response. - :paramtype role: str - :keyword content: Required. - :paramtype content: list[~azure.search.documents.agent.models.KnowledgeAgentMessageContent] - """ - super().__init__(**kwargs) - self.role = role - self.content = content - - -class KnowledgeAgentMessageContent(_serialization.Model): - """Specifies the type of the message content. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeAgentMessageImageContent, KnowledgeAgentMessageTextContent - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the message. Required. Known values are: "text" and "image". - :vartype type: str or ~azure.search.documents.agent.models.KnowledgeAgentMessageContentType - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - } - - _subtype_map = {"type": {"image": "KnowledgeAgentMessageImageContent", "text": "KnowledgeAgentMessageTextContent"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - - -class KnowledgeAgentMessageImageContent(KnowledgeAgentMessageContent): - """Text message type. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the message. Required. Known values are: "text" and "image". - :vartype type: str or ~azure.search.documents.agent.models.KnowledgeAgentMessageContentType - :ivar image: Required. - :vartype image: ~azure.search.documents.agent.models.KnowledgeAgentMessageImageContentImage - """ - - _validation = { - "type": {"required": True}, - "image": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "image": {"key": "image", "type": "KnowledgeAgentMessageImageContentImage"}, - } - - def __init__(self, *, image: "_models.KnowledgeAgentMessageImageContentImage", **kwargs: Any) -> None: - """ - :keyword image: Required. - :paramtype image: ~azure.search.documents.agent.models.KnowledgeAgentMessageImageContentImage - """ - super().__init__(**kwargs) - self.type: str = "image" - self.image = image - - -class KnowledgeAgentMessageImageContentImage(_serialization.Model): - """KnowledgeAgentMessageImageContentImage. - - All required parameters must be populated in order to send to server. - - :ivar url: The url of the image. Required. - :vartype url: str - """ - - _validation = { - "url": {"required": True}, - } - - _attribute_map = { - "url": {"key": "url", "type": "str"}, - } - - def __init__(self, *, url: str, **kwargs: Any) -> None: - """ - :keyword url: The url of the image. Required. - :paramtype url: str - """ - super().__init__(**kwargs) - self.url = url - - -class KnowledgeAgentMessageTextContent(KnowledgeAgentMessageContent): - """Text message type. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the message. Required. Known values are: "text" and "image". - :vartype type: str or ~azure.search.documents.agent.models.KnowledgeAgentMessageContentType - :ivar text: Required. - :vartype text: str - """ - - _validation = { - "type": {"required": True}, - "text": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "text": {"key": "text", "type": "str"}, - } - - def __init__(self, *, text: str, **kwargs: Any) -> None: - """ - :keyword text: Required. - :paramtype text: str - """ - super().__init__(**kwargs) - self.type: str = "text" - self.text = text - - -class KnowledgeAgentModelAnswerSynthesisActivityRecord(KnowledgeAgentActivityRecord): # pylint: disable=name-too-long - """Represents an LLM answer synthesis activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar input_tokens: The number of input tokens for the LLM answer synthesis activity. - :vartype input_tokens: int - :ivar output_tokens: The number of output tokens for the LLM answer synthesis activity. - :vartype output_tokens: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "input_tokens": {"key": "inputTokens", "type": "int"}, - "output_tokens": {"key": "outputTokens", "type": "int"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - input_tokens: Optional[int] = None, - output_tokens: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword input_tokens: The number of input tokens for the LLM answer synthesis activity. - :paramtype input_tokens: int - :keyword output_tokens: The number of output tokens for the LLM answer synthesis activity. - :paramtype output_tokens: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, **kwargs) - self.type: str = "modelAnswerSynthesis" - self.input_tokens = input_tokens - self.output_tokens = output_tokens - - -class KnowledgeAgentModelQueryPlanningActivityRecord(KnowledgeAgentActivityRecord): # pylint: disable=name-too-long - """Represents an LLM query planning activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar input_tokens: The number of input tokens for the LLM query planning activity. - :vartype input_tokens: int - :ivar output_tokens: The number of output tokens for the LLM query planning activity. - :vartype output_tokens: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "input_tokens": {"key": "inputTokens", "type": "int"}, - "output_tokens": {"key": "outputTokens", "type": "int"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - input_tokens: Optional[int] = None, - output_tokens: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword input_tokens: The number of input tokens for the LLM query planning activity. - :paramtype input_tokens: int - :keyword output_tokens: The number of output tokens for the LLM query planning activity. - :paramtype output_tokens: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, **kwargs) - self.type: str = "modelQueryPlanning" - self.input_tokens = input_tokens - self.output_tokens = output_tokens - - -class KnowledgeAgentRetrievalRequest(_serialization.Model): - """The input contract for the retrieval request. - - All required parameters must be populated in order to send to server. - - :ivar messages: Required. - :vartype messages: list[~azure.search.documents.agent.models.KnowledgeAgentMessage] - :ivar knowledge_source_params: - :vartype knowledge_source_params: - list[~azure.search.documents.agent.models.KnowledgeSourceParams] - """ - - _validation = { - "messages": {"required": True}, - } - - _attribute_map = { - "messages": {"key": "messages", "type": "[KnowledgeAgentMessage]"}, - "knowledge_source_params": {"key": "knowledgeSourceParams", "type": "[KnowledgeSourceParams]"}, - } - - def __init__( - self, - *, - messages: list["_models.KnowledgeAgentMessage"], - knowledge_source_params: Optional[list["_models.KnowledgeSourceParams"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword messages: Required. - :paramtype messages: list[~azure.search.documents.agent.models.KnowledgeAgentMessage] - :keyword knowledge_source_params: - :paramtype knowledge_source_params: - list[~azure.search.documents.agent.models.KnowledgeSourceParams] - """ - super().__init__(**kwargs) - self.messages = messages - self.knowledge_source_params = knowledge_source_params - - -class KnowledgeAgentRetrievalResponse(_serialization.Model): - """The output contract for the retrieval response. - - :ivar response: - :vartype response: list[~azure.search.documents.agent.models.KnowledgeAgentMessage] - :ivar activity: The activity records for tracking progress and billing implications. - :vartype activity: list[~azure.search.documents.agent.models.KnowledgeAgentActivityRecord] - :ivar references: The references for the retrieval data used in the response. - :vartype references: list[~azure.search.documents.agent.models.KnowledgeAgentReference] - """ - - _attribute_map = { - "response": {"key": "response", "type": "[KnowledgeAgentMessage]"}, - "activity": {"key": "activity", "type": "[KnowledgeAgentActivityRecord]"}, - "references": {"key": "references", "type": "[KnowledgeAgentReference]"}, - } - - def __init__( - self, - *, - response: Optional[list["_models.KnowledgeAgentMessage"]] = None, - activity: Optional[list["_models.KnowledgeAgentActivityRecord"]] = None, - references: Optional[list["_models.KnowledgeAgentReference"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword response: - :paramtype response: list[~azure.search.documents.agent.models.KnowledgeAgentMessage] - :keyword activity: The activity records for tracking progress and billing implications. - :paramtype activity: list[~azure.search.documents.agent.models.KnowledgeAgentActivityRecord] - :keyword references: The references for the retrieval data used in the response. - :paramtype references: list[~azure.search.documents.agent.models.KnowledgeAgentReference] - """ - super().__init__(**kwargs) - self.response = response - self.activity = activity - self.references = references - - -class KnowledgeAgentSearchIndexActivityArguments(_serialization.Model): # pylint: disable=name-too-long - """Represents the arguments the search index retrieval activity was run with. - - :ivar search: The search string used to query the search index. - :vartype search: str - :ivar filter: The filter string. - :vartype filter: str - """ - - _attribute_map = { - "search": {"key": "search", "type": "str"}, - "filter": {"key": "filter", "type": "str"}, - } - - def __init__( - self, - *, - search: Optional[str] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - **kwargs: Any - ) -> None: - """ - :keyword search: The search string used to query the search index. - :paramtype search: str - :keyword filter: The filter string. - :paramtype filter: str - """ - super().__init__(**kwargs) - self.search = search - self.filter = filter - - -class KnowledgeAgentSearchIndexActivityRecord(KnowledgeAgentRetrievalActivityRecord): - """Represents a search index retrieval activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar knowledge_source_name: The knowledge source for the retrieval activity. - :vartype knowledge_source_name: str - :ivar query_time: The query time for this retrieval activity. - :vartype query_time: ~datetime.datetime - :ivar count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :vartype count: int - :ivar search_index_arguments: The search index arguments for the retrieval activity. - :vartype search_index_arguments: - ~azure.search.documents.agent.models.KnowledgeAgentSearchIndexActivityArguments - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "query_time": {"key": "queryTime", "type": "iso-8601"}, - "count": {"key": "count", "type": "int"}, - "search_index_arguments": {"key": "searchIndexArguments", "type": "KnowledgeAgentSearchIndexActivityArguments"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - knowledge_source_name: Optional[str] = None, - query_time: Optional[datetime.datetime] = None, - count: Optional[int] = None, - search_index_arguments: Optional["_models.KnowledgeAgentSearchIndexActivityArguments"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword knowledge_source_name: The knowledge source for the retrieval activity. - :paramtype knowledge_source_name: str - :keyword query_time: The query time for this retrieval activity. - :paramtype query_time: ~datetime.datetime - :keyword count: The count of documents retrieved that were sufficiently relevant to pass the - reranker threshold. - :paramtype count: int - :keyword search_index_arguments: The search index arguments for the retrieval activity. - :paramtype search_index_arguments: - ~azure.search.documents.agent.models.KnowledgeAgentSearchIndexActivityArguments - """ - super().__init__( - id=id, - elapsed_ms=elapsed_ms, - knowledge_source_name=knowledge_source_name, - query_time=query_time, - count=count, - **kwargs - ) - self.type: str = "searchIndex" - self.search_index_arguments = search_index_arguments - - -class KnowledgeAgentSearchIndexReference(KnowledgeAgentReference): - """Represents an Azure Search document reference. - - All required parameters must be populated in order to send to server. - - :ivar type: The type of the reference. Required. - :vartype type: str - :ivar id: The ID of the reference. Required. - :vartype id: str - :ivar activity_source: The source activity ID for the reference. Required. - :vartype activity_source: int - :ivar source_data: Dictionary of :code:``. - :vartype source_data: dict[str, any] - :ivar reranker_score: The reranker score for the document reference. - :vartype reranker_score: float - :ivar doc_key: The document key for the reference. - :vartype doc_key: str - """ - - _validation = { - "type": {"required": True}, - "id": {"required": True}, - "activity_source": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "activity_source": {"key": "activitySource", "type": "int"}, - "source_data": {"key": "sourceData", "type": "{object}"}, - "reranker_score": {"key": "rerankerScore", "type": "float"}, - "doc_key": {"key": "docKey", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - activity_source: int, - source_data: Optional[dict[str, Any]] = None, - reranker_score: Optional[float] = None, - doc_key: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the reference. Required. - :paramtype id: str - :keyword activity_source: The source activity ID for the reference. Required. - :paramtype activity_source: int - :keyword source_data: Dictionary of :code:``. - :paramtype source_data: dict[str, any] - :keyword reranker_score: The reranker score for the document reference. - :paramtype reranker_score: float - :keyword doc_key: The document key for the reference. - :paramtype doc_key: str - """ - super().__init__( - id=id, activity_source=activity_source, source_data=source_data, reranker_score=reranker_score, **kwargs - ) - self.type: str = "searchIndex" - self.doc_key = doc_key - - -class KnowledgeAgentSemanticRerankerActivityRecord(KnowledgeAgentActivityRecord): # pylint: disable=name-too-long - """Represents a semantic ranker activity record. - - All required parameters must be populated in order to send to server. - - :ivar id: The ID of the activity record. Required. - :vartype id: int - :ivar type: The type of the activity record. Required. - :vartype type: str - :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :vartype elapsed_ms: int - :ivar input_tokens: The number of input tokens for the semantic ranker activity. - :vartype input_tokens: int - """ - - _validation = { - "id": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "int"}, - "type": {"key": "type", "type": "str"}, - "elapsed_ms": {"key": "elapsedMs", "type": "int"}, - "input_tokens": {"key": "inputTokens", "type": "int"}, - } - - def __init__( - self, - *, - id: int, # pylint: disable=redefined-builtin - elapsed_ms: Optional[int] = None, - input_tokens: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The ID of the activity record. Required. - :paramtype id: int - :keyword elapsed_ms: The elapsed time in milliseconds for the retrieval activity. - :paramtype elapsed_ms: int - :keyword input_tokens: The number of input tokens for the semantic ranker activity. - :paramtype input_tokens: int - """ - super().__init__(id=id, elapsed_ms=elapsed_ms, **kwargs) - self.type: str = "semanticReranker" - self.input_tokens = input_tokens - - -class KnowledgeSourceParams(_serialization.Model): - """KnowledgeSourceParams. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - SearchIndexKnowledgeSourceParams - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex" and - "azureBlob". - :vartype kind: str or ~azure.search.documents.agent.models.KnowledgeSourceKind - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = {"kind": {"searchIndex": "SearchIndexKnowledgeSourceParams"}} - - def __init__(self, *, knowledge_source_name: str, **kwargs: Any) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - """ - super().__init__(**kwargs) - self.knowledge_source_name = knowledge_source_name - self.kind: Optional[str] = None - - -class RequestOptions(_serialization.Model): - """Parameter group. - - :ivar x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :vartype x_ms_client_request_id: str - """ - - _attribute_map = { - "x_ms_client_request_id": {"key": "x-ms-client-request-id", "type": "str"}, - } - - def __init__(self, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :paramtype x_ms_client_request_id: str - """ - super().__init__(**kwargs) - self.x_ms_client_request_id = x_ms_client_request_id - - -class SearchIndexKnowledgeSourceParams(KnowledgeSourceParams): - """Specifies runtime parameters for a search index knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_source_name: The name of the index the params apply to. Required. - :vartype knowledge_source_name: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex" and - "azureBlob". - :vartype kind: str or ~azure.search.documents.agent.models.KnowledgeSourceKind - :ivar filter_add_on: A filter condition applied to the index (e.g., 'State eq VA'). - :vartype filter_add_on: str - """ - - _validation = { - "knowledge_source_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "knowledge_source_name": {"key": "knowledgeSourceName", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "filter_add_on": {"key": "filterAddOn", "type": "str"}, - } - - def __init__(self, *, knowledge_source_name: str, filter_add_on: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword knowledge_source_name: The name of the index the params apply to. Required. - :paramtype knowledge_source_name: str - :keyword filter_add_on: A filter condition applied to the index (e.g., 'State eq VA'). - :paramtype filter_add_on: str - """ - super().__init__(knowledge_source_name=knowledge_source_name, **kwargs) - self.kind: str = "searchIndex" - self.filter_add_on = filter_add_on diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/_knowledge_retrieval_operations.py b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/_knowledge_retrieval_operations.py deleted file mode 100644 index cf6369b46890..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/_knowledge_retrieval_operations.py +++ /dev/null @@ -1,228 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import KnowledgeAgentRetrievalClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_retrieve_request( - *, - x_ms_client_request_id: Optional[str] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/retrieve") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if x_ms_query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "x_ms_query_source_authorization", x_ms_query_source_authorization, "str" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class KnowledgeRetrievalOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.agent.KnowledgeAgentRetrievalClient`'s - :attr:`knowledge_retrieval` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: KnowledgeAgentRetrievalClientConfiguration = ( - input_args.pop(0) if input_args else kwargs.pop("config") - ) - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def retrieve( - self, - retrieval_request: _models.KnowledgeAgentRetrievalRequest, - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgentRetrievalResponse: - """KnowledgeAgent retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Required. - :type retrieval_request: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalRequest - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.agent.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgentRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def retrieve( - self, - retrieval_request: IO[bytes], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgentRetrievalResponse: - """KnowledgeAgent retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Required. - :type retrieval_request: IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.agent.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgentRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def retrieve( - self, - retrieval_request: Union[_models.KnowledgeAgentRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeAgentRetrievalResponse: - """KnowledgeAgent retrieves relevant data from backing stores. - - :param retrieval_request: The retrieval request to process. Is either a - KnowledgeAgentRetrievalRequest type or a IO[bytes] type. Required. - :type retrieval_request: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalRequest or - IO[bytes] - :param x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :type x_ms_query_source_authorization: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.agent.models.RequestOptions - :return: KnowledgeAgentRetrievalResponse or the result of cls(response) - :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeAgentRetrievalResponse] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieval_request, (IOBase, bytes)): - _content = retrieval_request - else: - _json = self._serialize.body(retrieval_request, "KnowledgeAgentRetrievalRequest") - - _request = build_retrieve_request( - x_ms_client_request_id=_x_ms_client_request_id, - x_ms_query_source_authorization=x_ms_query_source_authorization, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "agentName": self._serialize.url("self._config.agent_name", self._config.agent_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgentRetrievalResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/py.typed b/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/agent/aio/__init__.py deleted file mode 100644 index 18d9cc8b759e..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/aio/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from ._agent_client_async import KnowledgeAgentRetrievalClient - -__all__ = ("KnowledgeAgentRetrievalClient",) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/aio/_agent_client_async.py b/sdk/search/azure-search-documents/azure/search/documents/agent/aio/_agent_client_async.py deleted file mode 100644 index de658044da46..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/aio/_agent_client_async.py +++ /dev/null @@ -1,98 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, Any, Optional, IO - -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator_async import distributed_trace_async -from ..._utils import get_authentication_policy -from .._generated.aio import KnowledgeAgentRetrievalClient as _KnowledgeAgentRetrievalClient -from .._generated.models import ( - KnowledgeAgentRetrievalRequest, - RequestOptions, - KnowledgeAgentRetrievalResponse, -) -from ..._api_versions import DEFAULT_VERSION -from ..._headers_mixin import HeadersMixin -from ..._version import SDK_MONIKER - - -class KnowledgeAgentRetrievalClient(HeadersMixin): - """A client that can be used to query an agent. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: _KnowledgeAgentRetrievalClient - - def __init__( - self, endpoint: str, agent_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint: str = endpoint - self._agent_name: str = agent_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _KnowledgeAgentRetrievalClient( - endpoint=endpoint, - agent_name=agent_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = _KnowledgeAgentRetrievalClient( - endpoint=endpoint, - agent_name=agent_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self.knowledge_retrieval = self._client.knowledge_retrieval - - def __repr__(self) -> str: - return "".format( - repr(self._endpoint), repr(self._agent_name) - )[:1024] - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - @distributed_trace_async - async def retrieve( - self, - retrieval_request: Union[KnowledgeAgentRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[RequestOptions] = None, - **kwargs: Any - ) -> KnowledgeAgentRetrievalResponse: - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return await self._client.knowledge_retrieval.retrieve( - retrieval_request=retrieval_request, - x_ms_query_source_authorization=x_ms_query_source_authorization, - request_options=request_options, - **kwargs - ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/agent/models/__init__.py deleted file mode 100644 index 50cfc2635a57..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/models/__init__.py +++ /dev/null @@ -1,78 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from .._generated.models import ( - KnowledgeAgentActivityRecord, - KnowledgeAgentAzureBlobActivityArguments, - KnowledgeAgentAzureBlobActivityRecord, - KnowledgeAgentAzureBlobReference, - KnowledgeAgentMessage, - KnowledgeAgentMessageContent, - KnowledgeAgentMessageContentType, - KnowledgeAgentMessageImageContent, - KnowledgeAgentMessageImageContentImage, - KnowledgeAgentMessageTextContent, - KnowledgeAgentModelAnswerSynthesisActivityRecord, - KnowledgeAgentModelQueryPlanningActivityRecord, - KnowledgeAgentReference, - KnowledgeAgentRetrievalActivityRecord, - KnowledgeAgentRetrievalRequest, - KnowledgeAgentRetrievalResponse, - KnowledgeAgentSearchIndexActivityArguments, - KnowledgeAgentSearchIndexActivityRecord, - KnowledgeAgentSearchIndexReference, - KnowledgeAgentSemanticRerankerActivityRecord, - KnowledgeSourceParams, - RequestOptions, - SearchIndexKnowledgeSourceParams, -) - - -__all__ = ( - "KnowledgeAgentActivityRecord", - "KnowledgeAgentAzureBlobActivityArguments", - "KnowledgeAgentAzureBlobActivityRecord", - "KnowledgeAgentAzureBlobReference", - "KnowledgeAgentMessage", - "KnowledgeAgentMessageContent", - "KnowledgeAgentMessageContentType", - "KnowledgeAgentMessageImageContent", - "KnowledgeAgentMessageImageContentImage", - "KnowledgeAgentMessageTextContent", - "KnowledgeAgentModelAnswerSynthesisActivityRecord", - "KnowledgeAgentModelQueryPlanningActivityRecord", - "KnowledgeAgentReference", - "KnowledgeAgentRetrievalActivityRecord", - "KnowledgeAgentRetrievalRequest", - "KnowledgeAgentRetrievalResponse", - "KnowledgeAgentSearchIndexActivityArguments", - "KnowledgeAgentSearchIndexActivityRecord", - "KnowledgeAgentSearchIndexReference", - "KnowledgeAgentSemanticRerankerActivityRecord", - "KnowledgeSourceParams", - "RequestOptions", - "SearchIndexKnowledgeSourceParams", -) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py index c1a8ba78d5dd..79294ce3d7df 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/__init__.py @@ -1,34 +1,29 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._search_client_async import AsyncSearchItemPaged, SearchClient -from ._search_indexing_buffered_sender_async import SearchIndexingBufferedSender +from typing import TYPE_CHECKING -__all__ = ( - "AsyncSearchItemPaged", +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ "SearchClient", - "SearchIndexingBufferedSender", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py similarity index 69% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_search_index_client.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_client.py index 916d6e5380e5..427064b271ac 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_search_index_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py @@ -1,42 +1,58 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models from .._utils.serialization import Deserializer, Serializer -from ._configuration import SearchIndexClientConfiguration +from ._configuration import SearchClientConfiguration from .operations import DocumentsOperations +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class SearchIndexClient: - """Client that can be used to query an index and upload, merge, or delete documents. + +class SearchClient: + """SearchClient. :ivar documents: DocumentsOperations operations :vartype documents: azure.search.documents.aio.operations.DocumentsOperations - :param endpoint: The endpoint URL of the search service. Required. + :param endpoint: Service host. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential :param index_name: The name of the index. Required. :type index_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, index_name: str, **kwargs: Any + def __init__( + self, + endpoint: str, + credential: Union[AzureKeyCredential, "AsyncTokenCredential"], + index_name: str, + **kwargs: Any ) -> None: - _endpoint = "{endpoint}/indexes('{indexName}')" - self._config = SearchIndexClientConfiguration(endpoint=endpoint, index_name=index_name, **kwargs) + _endpoint = "{endpoint}" + self._config = SearchClientConfiguration( + endpoint=endpoint, credential=credential, index_name=index_name, **kwargs + ) _policies = kwargs.pop("policies", None) if _policies is None: @@ -57,13 +73,12 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.documents = DocumentsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -71,7 +86,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -86,7 +101,6 @@ def _send_request( request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "indexName": self._serialize.url("self._config.index_name", self._config.index_name, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py new file mode 100644 index 000000000000..34ad0564cab6 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_configuration.py @@ -0,0 +1,83 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class SearchClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, + endpoint: str, + credential: Union[AzureKeyCredential, "AsyncTokenCredential"], + index_name: str, + **kwargs: Any, + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if index_name is None: + raise ValueError("Parameter 'index_name' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.index_name = index_name + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py deleted file mode 100644 index 74f8d88c8b18..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py +++ /dev/null @@ -1,139 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import List, Union, Dict, Tuple, Any, cast -import asyncio # pylint: disable=do-not-import-asyncio - -from .._generated.models import IndexAction - - -def _flatten_args(args: Tuple[Union[List[Dict[Any, Any]], List[List[Dict[Any, Any]]]], ...]) -> List[Dict]: - if len(args) == 1 and isinstance(args[0], (list, tuple)): - return cast(List[Dict], args[0]) - return cast(List[Dict], args) - - -class IndexDocumentsBatch: - """Represent a batch of update operations for documents in an Azure - Search index. - - Index operations are performed in the order in which they are added - to the batch. - - """ - - def __init__(self) -> None: - self._actions: List[IndexAction] = [] - self._lock = asyncio.Lock() - - def __repr__(self) -> str: - return "".format(len(self.actions))[:1024] - - async def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to upload to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: Documents to upload to an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "upload") - - async def add_delete_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to delete to the Azure search index. - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: Documents to delete from an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "delete") - - async def add_merge_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to merge in to existing documents in the Azure search - index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - - :param documents: Documents to merge into an Azure search index. May be - a single list of documents, or documents as individual parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "merge") - - async def add_merge_or_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]: - """Add documents to merge in to existing documents in the Azure search - index, or upload if they do not yet exist. - - This action behaves like *merge* if a document with the given key - already exists in the index. If the document does not exist, it behaves - like *upload* with a new document. - - :param documents: Documents to merge or upload into an Azure search - index. May be a single list of documents, or documents as individual - parameters. - :type documents: dict or list[dict] - :return: the added actions - :rtype: list[IndexAction] - """ - return await self._extend_batch(_flatten_args(documents), "mergeOrUpload") - - @property - def actions(self) -> List[IndexAction]: - """The list of currently index actions to index. - - :rtype: list[IndexAction] - """ - return list(self._actions) - - async def dequeue_actions(self) -> List[IndexAction]: - """Get the list of currently configured index actions and clear it. - - :return: the list of currently configured index actions - :rtype: list[IndexAction] - """ - async with self._lock: - result = list(self._actions) - self._actions = [] - return result - - async def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction]]) -> None: - """Enqueue a list of index actions to index. - - :param new_actions: the list of index actions to enqueue - :type new_actions: list[IndexAction] - """ - if isinstance(new_actions, IndexAction): - async with self._lock: - self._actions.append(new_actions) - else: - async with self._lock: - self._actions.extend(new_actions) - - async def _extend_batch(self, documents: List[Dict], action_type: str) -> List[IndexAction]: - new_actions = [IndexAction(additional_properties=document, action_type=action_type) for document in documents] - async with self._lock: - self._actions.extend(new_actions) - return new_actions diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py deleted file mode 100644 index 51003804f4c1..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_paging.py +++ /dev/null @@ -1,164 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import List, Dict, Optional, cast, MutableMapping, Any - -from azure.core.paging import ReturnType -from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator -from .._generated.models import QueryAnswerResult, SearchDocumentsResult, DebugInfo -from .._paging import ( - convert_search_result, - pack_continuation_token, - unpack_continuation_token, -) -from .._api_versions import DEFAULT_VERSION - - -class AsyncSearchItemPaged(AsyncItemPaged[ReturnType]): - """A pageable list of search results.""" - - def __init__(self, *args, **kwargs) -> None: - super(AsyncSearchItemPaged, self).__init__(*args, **kwargs) - self._first_page_iterator_instance: Optional[AsyncSearchPageIterator] = None - - async def __anext__(self) -> ReturnType: - if self._page_iterator is None: - self._page_iterator = self.by_page() - self._first_page_iterator_instance = cast(AsyncSearchPageIterator, self._page_iterator) - return await self.__anext__() - if self._page is None: - # Let it raise StopAsyncIteration - self._page = await self._page_iterator.__anext__() - return await self.__anext__() - try: - return await self._page.__anext__() - except StopAsyncIteration: - self._page = None - return await self.__anext__() - - def _first_iterator_instance(self) -> "AsyncSearchPageIterator": - if self._first_page_iterator_instance is None: - self._page_iterator = cast(AsyncSearchPageIterator, self.by_page()) - self._first_page_iterator_instance = self._page_iterator - return self._first_page_iterator_instance - - async def get_facets(self) -> Optional[Dict]: - """Return any facet results if faceting was requested. - - :return: Facet results. - :rtype: dict - """ - return cast(Dict, await self._first_iterator_instance().get_facets()) - - async def get_coverage(self) -> float: - """Return the coverage percentage, if `minimum_coverage` was - specificied for the query. - - :return: Coverage percentage. - :rtype: float - """ - return cast(float, await self._first_iterator_instance().get_coverage()) - - async def get_count(self) -> int: - """Return the count of results if `include_total_count` was - set for the query. - - :return: Count of results. - :rtype: int - """ - return cast(int, await self._first_iterator_instance().get_count()) - - async def get_answers(self) -> Optional[List[QueryAnswerResult]]: - """Return semantic answers. Only included if the semantic ranker is used - and answers are requested in the search query via the query_answer parameter. - - :return: Answers. - :rtype: list[~azure.search.documents.models.QueryAnswerResult] - """ - return cast(List[QueryAnswerResult], await self._first_iterator_instance().get_answers()) - - async def get_debug_info(self) -> DebugInfo: - """Return the debug information for the query. - - :return: the debug information for the query. - :rtype: ~azure.search.documents.models.DebugInfo - """ - return cast(DebugInfo, await self._first_iterator_instance().get_debug_info()) - - -# The pylint error silenced below seems spurious, as the inner wrapper does, in -# fact, become a method of the class when it is applied. -def _ensure_response(f): - # pylint:disable=protected-access - async def wrapper(self, *args, **kw): - if self._current_page is None: - self._response = await self._get_next(self.continuation_token) - self.continuation_token, self._current_page = await self._extract_data(self._response) - return await f(self, *args, **kw) - - return wrapper - - -class AsyncSearchPageIterator(AsyncPageIterator[ReturnType]): - """An iterator of search results.""" - - def __init__(self, client, initial_query, kwargs, continuation_token=None) -> None: - super(AsyncSearchPageIterator, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token, - ) - self._client = client - self._initial_query = initial_query - self._kwargs = kwargs - self._facets: Optional[MutableMapping[str, List[MutableMapping[str, Any]]]] = None - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - - async def _get_next_cb(self, continuation_token): - if continuation_token is None: - return await self._client.documents.search_post(search_request=self._initial_query.request, **self._kwargs) - - _next_link, next_page_request = unpack_continuation_token(continuation_token) - - return await self._client.documents.search_post(search_request=next_page_request, **self._kwargs) - - async def _extract_data_cb(self, response): - continuation_token = pack_continuation_token(response, api_version=self._api_version) - results = [convert_search_result(r) for r in response.results] - return continuation_token, results - - @_ensure_response - async def get_facets(self) -> Optional[MutableMapping[str, Any]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - facets = response.facets - if facets is not None and self._facets is None: - assert facets.items() is not None # Hint for mypy - self._facets = {k: [x.as_dict() for x in v] for k, v in facets.items()} - return self._facets - - @_ensure_response - async def get_coverage(self) -> float: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(float, response.coverage) - - @_ensure_response - async def get_count(self) -> int: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(int, response.count) - - @_ensure_response - async def get_answers(self) -> Optional[List[QueryAnswerResult]]: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return response.answers - - @_ensure_response - async def get_debug_info(self) -> DebugInfo: - self.continuation_token = None - response = cast(SearchDocumentsResult, self._response) - return cast(DebugInfo, response.debug_info) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py deleted file mode 100644 index 01a9541ae995..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_client_async.py +++ /dev/null @@ -1,743 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import cast, List, Union, Any, Optional, Dict, MutableMapping - -from azure.core.rest import HttpRequest, AsyncHttpResponse -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator_async import distributed_trace_async -from ._paging import AsyncSearchItemPaged, AsyncSearchPageIterator -from .._utils import get_authentication_policy, get_answer_query, get_rewrites_query -from .._generated.aio import SearchIndexClient -from .._generated.models import ( - AutocompleteMode, - AutocompleteRequest, - IndexAction, - IndexBatch, - IndexingResult, - QueryAnswerType, - QueryCaptionType, - QueryLanguage, - QuerySpellerType, - QueryType, - SearchMode, - ScoringStatistics, - VectorFilterMode, - VectorQuery, - SemanticErrorMode, - QueryRewritesType, - QueryDebugMode, - SuggestRequest, - HybridSearch, -) -from .._search_documents_error import RequestEntityTooLargeError -from .._index_documents_batch import IndexDocumentsBatch -from .._queries import AutocompleteQuery, SearchQuery, SuggestQuery -from .._api_versions import DEFAULT_VERSION -from .._headers_mixin import HeadersMixin -from .._version import SDK_MONIKER - - -class SearchClient(HeadersMixin): - """A client to interact with an existing Azure search index. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param index_name: The name of the index to connect to - :type index_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_authentication_async.py - :start-after: [START create_search_client_with_key_async] - :end-before: [END create_search_client_with_key_async] - :language: python - :dedent: 4 - :caption: Creating the SearchClient with an API key. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: SearchIndexClient - - def __init__( - self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any - ) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._index_documents_batch = IndexDocumentsBatch() - self._endpoint: str = endpoint - self._index_name: str = index_name - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __repr__(self) -> str: - return "".format(repr(self._endpoint), repr(self._index_name))[:1024] - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - @distributed_trace_async - async def get_document_count(self, **kwargs: Any) -> int: - """Return the number of documents in the Azure search index. - - :return: The count of documents in the index - :rtype: int - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return int(await self._client.documents.count(**kwargs)) - - @distributed_trace_async - async def get_document(self, key: str, selected_fields: Optional[List[str]] = None, **kwargs: Any) -> Dict: - """Retrieve a document from the Azure search index by its key. - - :param key: The primary key value for the document to retrieve - :type key: str - :param selected_fields: an allow-list of fields to include in the results - :type selected_fields: list[str] - :return: The document that matches the specified key - :rtype: dict - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_get_document_async.py - :start-after: [START get_document_async] - :end-before: [END get_document_async] - :language: python - :dedent: 4 - :caption: Get a specific document from the search index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.documents.get(key=key, selected_fields=selected_fields, **kwargs) - return cast(dict, result) - - @distributed_trace_async - async def search( - self, - search_text: Optional[str] = None, - *, - include_total_count: Optional[bool] = None, - facets: Optional[List[str]] = None, - filter: Optional[str] = None, - highlight_fields: Optional[str] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - query_type: Optional[Union[str, QueryType]] = None, - scoring_parameters: Optional[List[str]] = None, - scoring_profile: Optional[str] = None, - semantic_query: Optional[str] = None, - search_fields: Optional[List[str]] = None, - search_mode: Optional[Union[str, SearchMode]] = None, - query_language: Optional[Union[str, QueryLanguage]] = None, - query_speller: Optional[Union[str, QuerySpellerType]] = None, - query_answer: Optional[Union[str, QueryAnswerType]] = None, - query_answer_count: Optional[int] = None, - query_answer_threshold: Optional[float] = None, - query_caption: Optional[Union[str, QueryCaptionType]] = None, - query_caption_highlight_enabled: Optional[bool] = None, - semantic_fields: Optional[List[str]] = None, - semantic_configuration_name: Optional[str] = None, - select: Optional[List[str]] = None, - skip: Optional[int] = None, - top: Optional[int] = None, - scoring_statistics: Optional[Union[str, ScoringStatistics]] = None, - session_id: Optional[str] = None, - vector_queries: Optional[List[VectorQuery]] = None, - vector_filter_mode: Optional[Union[str, VectorFilterMode]] = None, - semantic_error_mode: Optional[Union[str, SemanticErrorMode]] = None, - semantic_max_wait_in_milliseconds: Optional[int] = None, - query_rewrites: Optional[Union[str, QueryRewritesType]] = None, - query_rewrites_count: Optional[int] = None, - debug: Optional[Union[str, QueryDebugMode]] = None, - hybrid_search: Optional[HybridSearch] = None, - x_ms_query_source_authorization: Optional[str] = None, - **kwargs - ) -> AsyncSearchItemPaged[Dict]: - # pylint:disable=too-many-locals, disable=redefined-builtin - """Search the Azure search index for documents. - - :param str search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. - :keyword bool include_total_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :keyword list[str] facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. - :keyword str filter: The OData $filter expression to apply to the search query. - :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is . - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is . - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, and - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no OrderBy is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: - 'simple', 'full', "semantic". - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword list[str] scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). - :keyword str scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. - :keyword str semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. - :keyword list[str] search_fields: The list of field names to which to scope the full-text search. When - using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of - each fielded search expression take precedence over any field names listed in this parameter. - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Possible values include: 'any', 'all'. - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: The language of the search query. Possible values include: "none", "en-us", - "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", - "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", - "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", - "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", - "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", - "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", - "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk". - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Possible values include: "none", "lexicon". - :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword query_answer: This parameter is only valid if the query type is 'semantic'. If set, - the query returns answers extracted from key passages in the highest ranked documents. - Possible values include: "none", "extractive". - :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType - :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. - Configures the number of answers returned. Default count is 1. - :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and - query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. - :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the - query returns captions extracted from key passages in the highest ranked documents. - Defaults to 'None'. Possible values include: "none", "extractive". - :paramtype query_caption: str or ~azure.search.documents.models.QueryCaptionType - :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when - query caption is set to 'extractive'. Determines whether highlighting is enabled. - Defaults to 'true'. - :keyword list[str] semantic_fields: The list of field names used for semantic search. - :keyword semantic_configuration_name: The name of the semantic configuration that will be used when - processing documents for queries of type semantic. - :paramtype semantic_configuration_name: str - :keyword list[str] select: The list of fields to retrieve. If unspecified, all fields marked as retrievable - in the schema are included. - :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use $skip due to this limitation, - consider using $orderby on a totally-ordered key and $filter with a range query instead. - :keyword int top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. - Possible values include: "local", "global". - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword str session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. - :keyword semantic_error_mode: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". - :paramtype semantic_error_mode: str or ~azure.search.documents.models.SemanticErrorMode - :keyword int semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of - time it takes for semantic enrichment to finish processing before the request fails. - :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent - to a generate model which will produce 10 (default) rewrites to help increase the recall of the - request. The requested count can be configured by appending the pipe character ``|`` followed - by the ``count-`` option, such as ``generative|count-3``. Defaults to - ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: - "none" and "generative". - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword int query_rewrites_count: This parameter is only valid if the query rewrites type is 'generative'. - Configures the number of rewrites returned. Default count is 10. - :keyword debug: Enables a debugging tool that can be used to further explore your Semantic search - results. Known values are: "disabled", "speller", "semantic", and "all". - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword vector_queries: The query parameters for vector and hybrid search queries. - :paramtype vector_queries: list[VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". - :paramtype vector_filter_mode: str or VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - :keyword x_ms_query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype x_ms_query_source_authorization: str - :return: A list of documents (dicts) matching the specified search criteria. - :return: List of search results. - :rtype: AsyncSearchItemPaged[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_simple_query_async.py - :start-after: [START simple_query_async] - :end-before: [END simple_query_async] - :language: python - :dedent: 4 - :caption: Search on a simple text term. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_filter_query_async.py - :start-after: [START filter_query_async] - :end-before: [END filter_query_async] - :language: python - :dedent: 4 - :caption: Filter and sort search results. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_facet_query_async.py - :start-after: [START facet_query_async] - :end-before: [END facet_query_async] - :language: python - :dedent: 4 - :caption: Get search result facets. - """ - include_total_result_count = include_total_count - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - answers = get_answer_query(query_answer, query_answer_count, query_answer_threshold) - rewrites = get_rewrites_query(query_rewrites, query_rewrites_count) - captions = ( - query_caption - if not query_caption_highlight_enabled - else "{}|highlight-{}".format(query_caption, query_caption_highlight_enabled) - ) - semantic_configuration = semantic_configuration_name - - query = SearchQuery( - search_text=search_text, - include_total_result_count=include_total_result_count, - facets=facets, - filter=filter_arg, - highlight_fields=highlight_fields, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - query_type=query_type, - scoring_parameters=scoring_parameters, - scoring_profile=scoring_profile, - semantic_query=semantic_query, - search_fields=search_fields_str, - search_mode=search_mode, - query_language=query_language, - speller=query_speller, - answers=answers, - captions=captions, - semantic_fields=",".join(semantic_fields) if semantic_fields else None, - semantic_configuration=semantic_configuration, - select=select if isinstance(select, str) else None, - skip=skip, - top=top, - session_id=session_id, - scoring_statistics=scoring_statistics, - vector_queries=vector_queries, - vector_filter_mode=vector_filter_mode, - semantic_error_handling=semantic_error_mode, - semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, - query_rewrites=rewrites, - debug=debug, - hybrid_search=hybrid_search, - ) - if isinstance(select, list): - query.select(select) - if isinstance(order_by, list): - query.order_by(order_by) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["x_ms_query_source_authorization"] = x_ms_query_source_authorization - kwargs["api_version"] = self._api_version - return AsyncSearchItemPaged(self._client, query, kwargs, page_iterator_class=AsyncSearchPageIterator) - - @distributed_trace_async - async def suggest( - self, - search_text: str, - suggester_name: str, - *, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, - top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search suggestion results from the Azure search index. - - :param str search_text: Required. The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. - :param str suggester_name: Required. The name of the suggester as specified in the suggesters - collection that's part of the index definition. - :keyword str filter: An OData expression that filters the documents considered for suggestions. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestions - query. Default is false. When set to true, the query will find terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestions queries are slower and - consume more resources. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestions query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] order_by: The list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses. - :keyword list[str] search_fields: The list of field names to search for the specified search text. Target - fields must be included in the specified suggester. - :keyword list[str] select: The list of fields to retrieve. If unspecified, only the key field will be - included in the results. - :keyword int top: The number of suggestions to retrieve. The value must be a number between 1 and - 100. The default is 5. - :return: List of suggestion results. - :rtype: list[dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_suggestions_async.py - :start-after: [START suggest_query_async] - :end-before: [END suggest_query_async] - :language: python - :dedent: 4 - :caption: Get search suggestions. - """ - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = SuggestQuery( - search_text=search_text, - suggester_name=suggester_name, - filter=filter_arg, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by if isinstance(order_by, str) else None, - search_fields=search_fields_str, - select=select if isinstance(select, str) else None, - top=top, - ) - if isinstance(select, list): - query.select(select) - if isinstance(order_by, list): - query.order_by(order_by) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(SuggestRequest, query.request) - response = await self._client.documents.suggest_post(suggest_request=request, **kwargs) - assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - @distributed_trace_async - async def autocomplete( - self, - search_text: str, - suggester_name: str, - *, - mode: Optional[Union[str, AutocompleteMode]] = None, - filter: Optional[str] = None, - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[List[str]] = None, - top: Optional[int] = None, - **kwargs - ) -> List[MutableMapping[str, Any]]: - """Get search auto-completion results from the Azure search index. - - :param str search_text: The search text on which to base autocomplete results. - :param str suggester_name: The name of the suggester as specified in the suggesters - collection that's part of the index definition. - :keyword mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Possible values include: 'oneTerm', 'twoTerms', 'oneTermWithContext'. - :paramtype mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword str filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will find terms even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. - :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :keyword list[str] search_fields: The list of field names to consider when querying for auto-completed - terms. Target fields must be included in the specified suggester. - :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :return: List of auto-completion results. - :rtype: list[Dict] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_autocomplete_async.py - :start-after: [START autocomplete_query_async] - :end-before: [END autocomplete_query_async] - :language: python - :dedent: 4 - :caption: Get a auto-completions. - """ - autocomplete_mode = mode - filter_arg = filter - search_fields_str = ",".join(search_fields) if search_fields else None - query = AutocompleteQuery( - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter_arg, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields_str, - top=top, - ) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - request = cast(AutocompleteRequest, query.request) - response = await self._client.documents.autocomplete_post(autocomplete_request=request, **kwargs) - assert response.results is not None # Hint for mypy - results = [r.as_dict() for r in response.results] - return results - - # pylint:disable=client-method-missing-tracing-decorator-async - async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Upload documents to the Azure search index. - - An upload action is similar to an "upsert" where the document will be - inserted if it is new and updated/replaced if it exists. All fields are - replaced in the update case. - - :param documents: A list of documents to upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py - :start-after: [START upload_document_async] - :end-before: [END upload_document_async] - :language: python - :dedent: 4 - :caption: Upload new documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator-async, delete-operation-wrong-return-type - async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Delete documents from the Azure search index - - Delete removes the specified document from the index. Any field you - specify in a delete operation, other than the key field, will be - ignored. If you want to remove an individual field from a document, use - `merge_documents` instead and set the field explicitly to None. - - Delete operations are idempotent. That is, even if a document key does - not exist in the index, attempting a delete operation with that key will - result in a 200 status code. - - :param documents: A list of documents to delete. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py - :start-after: [START delete_document_async] - :end-before: [END delete_document_async] - :language: python - :dedent: 4 - :caption: Delete existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_delete_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator-async - async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index. - - Merge updates an existing document with the specified fields. If the - document doesn't exist, the merge will fail. Any field you specify in a - merge will replace the existing field in the document. This also applies - to collections of primitive and complex types. - - :param documents: A list of documents to merge. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py - :start-after: [START merge_document_async] - :end-before: [END merge_document_async] - :language: python - :dedent: 4 - :caption: Merge fields into existing documents to an index - """ - batch = IndexDocumentsBatch() - batch.add_merge_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - # pylint:disable=client-method-missing-tracing-decorator-async - async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[IndexingResult]: - """Merge documents in to existing documents in the Azure search index, - or upload them if they do not yet exist. - - This action behaves like `merge_documents` if a document with the given - key already exists in the index. If the document does not exist, it - behaves like `upload_documents` with a new document. - - :param documents: A list of documents to merge or upload. - :type documents: list[dict] - :return: List of IndexingResult - :rtype: list[IndexingResult] - """ - batch = IndexDocumentsBatch() - batch.add_merge_or_upload_actions(documents) - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - results = await self.index_documents(batch, **kwargs) - return cast(List[IndexingResult], results) - - @distributed_trace_async - async def index_documents(self, batch: IndexDocumentsBatch, **kwargs: Any) -> List[IndexingResult]: - """Specify a document operations to perform as a batch. - - :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: List of IndexingResult - :rtype: list[IndexingResult] - - :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. - """ - return await self._index_documents_actions(actions=batch.actions, **kwargs) - - async def _index_documents_actions(self, actions: List[IndexAction], **kwargs: Any) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) - try: - batch_response = await self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) - except RequestEntityTooLargeError: - if len(actions) == 1: - raise - pos = round(len(actions) / 2) - batch_response_first_half = await self._index_documents_actions(actions=actions[:pos], **kwargs) - if batch_response_first_half: - result_first_half = batch_response_first_half - else: - result_first_half = [] - batch_response_second_half = await self._index_documents_actions(actions=actions[pos:], **kwargs) - if batch_response_second_half: - result_second_half = batch_response_second_half - else: - result_second_half = [] - result_first_half.extend(result_second_half) - return result_first_half - - async def __aenter__(self) -> "SearchClient": - await self._client.__aenter__() # pylint: disable=no-member - return self - - async def __aexit__(self, *args) -> None: - await self._client.__aexit__(*args) - - @distributed_trace_async - async def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> AsyncHttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return await self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py deleted file mode 100644 index 9990a7dca659..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py +++ /dev/null @@ -1,362 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import cast, List, Union, Any, Dict -import time - -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.exceptions import ServiceResponseTimeoutError -from ._timer import Timer -from .._utils import is_retryable_status_code, get_authentication_policy -from .._search_indexing_buffered_sender_base import SearchIndexingBufferedSenderBase -from .._generated.aio import SearchIndexClient -from .._generated.models import IndexingResult, IndexBatch, IndexAction -from .._search_documents_error import RequestEntityTooLargeError -from ._index_documents_batch_async import IndexDocumentsBatch -from .._headers_mixin import HeadersMixin -from .._version import SDK_MONIKER - - -class SearchIndexingBufferedSender(SearchIndexingBufferedSenderBase, HeadersMixin): - """A buffered sender for document indexing actions. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param index_name: The name of the index to connect to - :type index_name: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword int auto_flush_interval: how many max seconds if between 2 flushes. This only takes effect - when auto_flush is on. Default to 60 seconds. - :keyword int initial_batch_action_count: The initial number of actions to group into a batch when - tuning the behavior of the sender. The default value is 512. - :keyword int max_retries_per_action: The number of times to retry a failed document. The default value is 3. - :keyword callable on_new: If it is set, the client will call corresponding methods when there - is a new IndexAction added. - :keyword callable on_progress: If it is set, the client will call corresponding methods when there - is a IndexAction succeeds. - :keyword callable on_error: If it is set, the client will call corresponding methods when there - is a IndexAction fails. - :keyword callable on_remove: If it is set, the client will call corresponding methods when there - is a IndexAction removed from the queue (succeeds or fails). - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _client: SearchIndexClient - - # pylint: disable=too-many-instance-attributes - - def __init__( - self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any - ) -> None: - super(SearchIndexingBufferedSender, self).__init__( - endpoint=endpoint, index_name=index_name, credential=credential, **kwargs - ) - self._index_documents_batch = IndexDocumentsBatch() - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = SearchIndexClient( - endpoint=endpoint, - index_name=index_name, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - self._reset_timer() - - async def _cleanup(self, flush: bool = True) -> None: - """Clean up the client. - - :param bool flush: flush the actions queue before shutdown the client - Default to True. - """ - if flush: - await self.flush() - if self._auto_flush: - self._timer.cancel() - - def __repr__(self) -> str: - return "".format( - repr(self._endpoint), repr(self._index_name) - )[:1024] - - @property - def actions(self) -> List[IndexAction]: - """The list of currently index actions in queue to index. - - :return: The list of currently index actions in queue to index. - :rtype: list[IndexAction] - """ - return self._index_documents_batch.actions - - @distributed_trace_async - async def close(self, **kwargs: Any) -> None: # pylint: disable=unused-argument - """Close the session. - - :return: None - :rtype: None - """ - await self._cleanup(flush=True) - return await self._client.close() - - @distributed_trace_async - async def flush(self, timeout: int = 86400, **kwargs) -> bool: # pylint:disable=unused-argument - """Flush the batch. - - :param int timeout: time out setting. Default is 86400s (one day) - :return: True if there are errors. Else False - :rtype: bool - :raises ~azure.core.exceptions.ServiceResponseTimeoutError: if there is a timeout - """ - has_error = False - begin_time = int(time.time()) - while len(self.actions) > 0: - now = int(time.time()) - remaining = timeout - (now - begin_time) - if remaining < 0: - if self._on_error: - actions = await self._index_documents_batch.dequeue_actions() - for action in actions: - await self._on_error(action) - raise ServiceResponseTimeoutError("Service response time out") - result = await self._process(timeout=remaining, raise_error=False) - if result: - has_error = True - return has_error - - async def _process(self, timeout: int = 86400, **kwargs) -> bool: - from ..indexes.aio import SearchIndexClient as SearchServiceClient - - raise_error = kwargs.pop("raise_error", True) - actions = await self._index_documents_batch.dequeue_actions() - has_error = False - if not self._index_key: - try: - credential = cast(Union[AzureKeyCredential, AsyncTokenCredential], self._credential) - client = SearchServiceClient(self._endpoint, credential) - index_result = await client.get_index(self._index_name) - if index_result: - for field in index_result.fields: - if field.key: - self._index_key = field.name - break - except Exception: # pylint: disable=broad-except - pass - - self._reset_timer() - - try: - results = await self._index_documents_actions(actions=actions, timeout=timeout) - for result in results: - try: - assert self._index_key is not None # Hint for mypy - action = next( - x - for x in actions - if x.additional_properties and x.additional_properties.get(self._index_key) == result.key - ) - if result.succeeded: - await self._callback_succeed(action) - elif is_retryable_status_code(result.status_code): - await self._retry_action(action) - has_error = True - else: - await self._callback_fail(action) - has_error = True - except StopIteration: - pass - - return has_error - - except Exception: # pylint: disable=broad-except - for action in actions: - await self._retry_action(action) - if raise_error: - raise - return True - return has_error - - async def _process_if_needed(self) -> bool: - """Every time when a new action is queued, this method - will be triggered. It checks the actions already queued and flushes them if: - 1. Auto_flush is on - 2. There are self._batch_action_count actions queued - - :return: True if proces is needed, False otherwise - :rtype: bool - """ - if not self._auto_flush: - return False - - if len(self._index_documents_batch.actions) < self._batch_action_count: - return False - - return await self._process(raise_error=False) - - def _reset_timer(self): - # pylint: disable=access-member-before-definition - try: - self._timer.cancel() - except AttributeError: - pass - if self._auto_flush: - self._timer = Timer(self._auto_flush_interval, self._process) - - @distributed_trace_async - async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> None: # pylint: disable=unused-argument - """Queue upload documents actions. - - :param documents: A list of documents to upload. - :type documents: list[dict] - """ - actions = await self._index_documents_batch.add_upload_actions(documents) - await self._callback_new(actions) - await self._process_if_needed() - - @distributed_trace_async - async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> None: # pylint: disable=unused-argument - """Queue delete documents actions - - :param documents: A list of documents to delete. - :type documents: list[Dict] - """ - actions = await self._index_documents_batch.add_delete_actions(documents) - await self._callback_new(actions) - await self._process_if_needed() - - @distributed_trace_async - async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> None: # pylint: disable=unused-argument - """Queue merge documents actions - - :param documents: A list of documents to merge. - :type documents: list[dict] - """ - actions = await self._index_documents_batch.add_merge_actions(documents) - await self._callback_new(actions) - await self._process_if_needed() - - @distributed_trace_async - async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> None: - # pylint: disable=unused-argument - """Queue merge documents or upload documents actions - - :param documents: A list of documents to merge or upload. - :type documents: list[dict] - """ - actions = await self._index_documents_batch.add_merge_or_upload_actions(documents) - await self._callback_new(actions) - await self._process_if_needed() - - @distributed_trace_async - async def index_documents(self, batch: IndexDocumentsBatch, **kwargs: Any) -> List[IndexingResult]: - """Specify a document operations to perform as a batch. - - :param batch: A batch of document operations to perform. - :type batch: IndexDocumentsBatch - :return: Indexing result for each action in the batch. - :rtype: list[IndexingResult] - :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. - """ - return await self._index_documents_actions(actions=batch.actions, **kwargs) - - async def _index_documents_actions(self, actions: List[IndexAction], **kwargs: Any) -> List[IndexingResult]: - error_map = {413: RequestEntityTooLargeError} - - timeout = kwargs.pop("timeout", 86400) - begin_time = int(time.time()) - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - batch = IndexBatch(actions=actions) - try: - batch_response = await self._client.documents.index(batch=batch, error_map=error_map, **kwargs) - return cast(List[IndexingResult], batch_response.results) - except RequestEntityTooLargeError as ex: - if len(actions) == 1: - raise - pos = round(len(actions) / 2) - if pos < self._batch_action_count: - await self._index_documents_batch.enqueue_actions(actions) - now = int(time.time()) - remaining = timeout - (now - begin_time) - if remaining < 0: - raise ServiceResponseTimeoutError("Service response time out") from ex - batch_response_first_half = await self._index_documents_actions( - actions=actions[:pos], timeout=remaining, **kwargs - ) - if len(batch_response_first_half) > 0: - result_first_half = batch_response_first_half - else: - result_first_half = [] - now = int(time.time()) - remaining = timeout - (now - begin_time) - if remaining < 0: - raise ServiceResponseTimeoutError("Service response time out") from ex - batch_response_second_half = await self._index_documents_actions( - actions=actions[pos:], timeout=remaining, **kwargs - ) - if len(batch_response_second_half) > 0: - result_second_half = batch_response_second_half - else: - result_second_half = [] - result_first_half.extend(result_second_half) - return result_first_half - - async def __aenter__(self) -> "SearchIndexingBufferedSender": - await self._client.__aenter__() # pylint: disable=no-member - return self - - async def __aexit__(self, *args) -> None: - await self.close() - await self._client.__aexit__(*args) - - async def _retry_action(self, action: IndexAction) -> None: - if not self._index_key: - await self._callback_fail(action) - return - key = cast(str, action.additional_properties.get(self._index_key) if action.additional_properties else "") - counter = self._retry_counter.get(key) - if not counter: - # first time that fails - self._retry_counter[key] = 1 - await self._index_documents_batch.enqueue_actions(action) - elif counter < self._max_retries_per_action - 1: - # not reach retry limit yet - self._retry_counter[key] = counter + 1 - await self._index_documents_batch.enqueue_actions(action) - else: - await self._callback_fail(action) - - async def _callback_succeed(self, action: IndexAction) -> None: - if self._on_remove: - await self._on_remove(action) - if self._on_progress: - await self._on_progress(action) - - async def _callback_fail(self, action: IndexAction) -> None: - if self._on_remove: - await self._on_remove(action) - if self._on_error: - await self._on_error(action) - - async def _callback_new(self, actions: List[IndexAction]) -> None: - if self._on_new: - for action in actions: - await self._on_new(action) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py deleted file mode 100644 index 2bf58159a25c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_timer.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import asyncio # pylint: disable=do-not-import-asyncio - - -class Timer: - def __init__(self, timeout, callback) -> None: - self._timeout = timeout - self._callback = callback - self._task = asyncio.ensure_future(self._job()) - - async def _job(self): - await asyncio.sleep(self._timeout) - await self._callback() - - def cancel(self) -> None: - self._task.cancel() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/aio/operations/__init__.py similarity index 70% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/operations/__init__.py index de96b0faddf2..e7e958355b4b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._documents_operations import DocumentsOperations # type: ignore +from ._operations import DocumentsOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py new file mode 100644 index 000000000000..e04b0ff1cc1f --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py @@ -0,0 +1,1382 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2 +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ..._validation import api_version_validation +from ...operations._operations import ( + build_documents_autocomplete_get_request, + build_documents_autocomplete_post_request, + build_documents_count_request, + build_documents_get_request, + build_documents_index_request, + build_documents_search_get_request, + build_documents_search_post_request, + build_documents_suggest_get_request, + build_documents_suggest_post_request, +) +from .._configuration import SearchClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class DocumentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchClient`'s + :attr:`documents` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def count(self, *, query_source_authorization: Optional[str] = None, **kwargs: Any) -> int: + """Queries the number of documents in the index. + + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: int + :rtype: int + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[int] = kwargs.pop("cls", None) + + _request = build_documents_count_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(int, response.text()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + params_added_on={ + "2025-08-01-preview": ["query_rewrites", "debug", "query_language", "speller", "semantic_fields"] + }, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + async def search_get( + self, + *, + search_text: Optional[str] = None, + include_total_result_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[List[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + query_type: Optional[Union[str, _models2.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + search_fields: Optional[List[str]] = None, + search_mode: Optional[Union[str, _models2.SearchMode]] = None, + scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, + session_id: Optional[str] = None, + select: Optional[List[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models2.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + answers: Optional[Union[str, _models2.QueryAnswerType]] = None, + captions: Optional[Union[str, _models2.QueryCaptionType]] = None, + semantic_query: Optional[str] = None, + query_rewrites: Optional[Union[str, _models2.QueryRewritesType]] = None, + debug: Optional[Union[str, _models2.QueryDebugMode]] = None, + query_language: Optional[Union[str, _models2.QueryLanguage]] = None, + speller: Optional[Union[str, _models2.QuerySpellerType]] = None, + semantic_fields: Optional[List[str]] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword include_total_result_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_result_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The list of field names to use for hit highlights. Only searchable + fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: list[str] + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword search_fields: The list of field names to which to scope the full-text search. When + using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of + each fielded search expression take precedence over any field names listed in this parameter. + Default value is None. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. Known values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help to get more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as + retrievable in the schema are included. Default value is None. + :paramtype select: list[str] + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + Default value is None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration: The name of the semantic configuration that lists which fields + should be used for semantic ranking, captions, highlights, and answers. Default value is None. + :paramtype semantic_configuration: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely, or to return partial results (default). Known values are: "partial" and "fail". + Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword answers: This parameter is only valid if the query type is ``semantic``. If set, the + query returns answers extracted from key passages in the highest ranked documents. The number + of answers returned can be configured by appending the pipe character ``|`` followed by the + ``count-`` option after the answers parameter value, such as + ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by + appending the pipe character ``|`` followed by the ``threshold-`` option + after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is + 0.7. The maximum character length of answers can be configured by appending the pipe character + '|' followed by the 'count-', such as + 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". Default value is + None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: This parameter is only valid if the query type is ``semantic``. If set, the + query returns captions extracted from key passages in the highest ranked documents. When + Captions is set to ``extractive``, highlighting is enabled by default, and can be configured by + appending the pipe character ``|`` followed by the ``highlight-`` option, such as + ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of captions + can be configured by appending the pipe character '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. Known values are: "none" and + "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword query_rewrites: When QueryRewrites is set to ``generative``, the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword debug: Enables a debugging tool that can be used to further explore your search + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword query_language: The language of the query. Known values are: "none", "en-us", "en-gb", + "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", + "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", + "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", + "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", + "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", + "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". Default + value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword speller: Improve search recall by spell-correcting individual search query terms. + Known values are: "none" and "lexicon". Default value is None. + :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword semantic_fields: The list of field names used for semantic ranking. Default value is + None. + :paramtype semantic_fields: list[str] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchDocumentsResult] = kwargs.pop("cls", None) + + _request = build_documents_search_get_request( + index_name=self._config.index_name, + search_text=search_text, + include_total_result_count=include_total_result_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + search_fields=search_fields, + search_mode=search_mode, + scoring_statistics=scoring_statistics, + session_id=session_id, + select=select, + skip=skip, + top=top, + semantic_configuration=semantic_configuration, + semantic_error_handling=semantic_error_handling, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + answers=answers, + captions=captions, + semantic_query=semantic_query, + query_rewrites=query_rewrites, + debug=debug, + query_language=query_language, + speller=speller, + semantic_fields=semantic_fields, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def search_post( + self, + search_request: _models2.SearchRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Required. + :type search_request: ~azure.search.documents.models.SearchRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def search_post( + self, + search_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Required. + :type search_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def search_post( + self, + search_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Required. + :type search_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def search_post( + self, + search_request: Union[_models2.SearchRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Is one of the following types: + SearchRequest, JSON, IO[bytes] Required. + :type search_request: ~azure.search.documents.models.SearchRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(search_request, (IOBase, bytes)): + _content = search_request + else: + _content = json.dumps(search_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_search_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get( + self, + key: str, + *, + selected_fields: Optional[List[str]] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.LookupDocument: + """Retrieves a document from the index. + + :param key: The key of the document to retrieve. Required. + :type key: str + :keyword selected_fields: List of field names to retrieve for the document; Any field not + retrieved will be missing from the returned document. Default value is None. + :paramtype selected_fields: list[str] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: LookupDocument. The LookupDocument is compatible with MutableMapping + :rtype: ~azure.search.documents.models.LookupDocument + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.LookupDocument] = kwargs.pop("cls", None) + + _request = build_documents_get_request( + key=key, + index_name=self._config.index_name, + selected_fields=selected_fields, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.LookupDocument, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def suggest_get( + self, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + search_fields: Optional[List[str]] = None, + select: Optional[List[str]] = None, + top: Optional[int] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestions query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestions queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestions query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword search_fields: The list of field names to search for the specified search text. Target + fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword select: The list of fields to retrieve. If unspecified, only the key field will be + included in the results. Default value is None. + :paramtype select: list[str] + :keyword top: The number of suggestions to retrieve. The value must be a number between 1 and + 100. The default is 5. Default value is None. + :paramtype top: int + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SuggestDocumentsResult] = kwargs.pop("cls", None) + + _request = build_documents_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SuggestDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def suggest_post( + self, + suggest_request: _models2.SuggestRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Required. + :type suggest_request: ~azure.search.documents.models.SuggestRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def suggest_post( + self, + suggest_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Required. + :type suggest_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def suggest_post( + self, + suggest_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Required. + :type suggest_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def suggest_post( + self, + suggest_request: Union[_models2.SuggestRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Is one of the following types: SuggestRequest, + JSON, IO[bytes] Required. + :type suggest_request: ~azure.search.documents.models.SuggestRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SuggestDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(suggest_request, (IOBase, bytes)): + _content = suggest_request + else: + _content = json.dumps(suggest_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_suggest_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SuggestDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def index( + self, + batch: _models2.IndexBatch, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Required. + :type batch: ~azure.search.documents.models.IndexBatch + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def index( + self, + batch: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Required. + :type batch: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def index( + self, + batch: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Required. + :type batch: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def index( + self, + batch: Union[_models2.IndexBatch, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Is one of the following types: IndexBatch, JSON, + IO[bytes] Required. + :type batch: ~azure.search.documents.models.IndexBatch or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.IndexDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(batch, (IOBase, bytes)): + _content = batch + else: + _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_index_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 207]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.IndexDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def autocomplete_get( + self, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, _models2.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[List[str]] = None, + top: Optional[int] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :keyword search_text: The incomplete term which should be auto-completed. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The list of field names to consider when querying for auto-completed + terms. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.AutocompleteResult] = kwargs.pop("cls", None) + + _request = build_documents_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.AutocompleteResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def autocomplete_post( + self, + autocomplete_request: _models2.AutocompleteRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Required. + :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def autocomplete_post( + self, + autocomplete_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Required. + :type autocomplete_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def autocomplete_post( + self, + autocomplete_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Required. + :type autocomplete_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def autocomplete_post( + self, + autocomplete_request: Union[_models2.AutocompleteRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Is one of the + following types: AutocompleteRequest, JSON, IO[bytes] Required. + :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or JSON or + IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.AutocompleteResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(autocomplete_request, (IOBase, bytes)): + _content = autocomplete_request + else: + _content = json.dumps(autocomplete_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_autocomplete_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.AutocompleteResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py index 03792b2fcb89..db78bf894037 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py @@ -1,33 +1,32 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._search_index_client import SearchIndexClient -from ._search_indexer_client import SearchIndexerClient +from typing import TYPE_CHECKING -__all__ = ( - "SearchIndexerClient", +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchIndexClient # type: ignore +from .._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ "SearchIndexClient", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py similarity index 61% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py index 7fccc649dc7f..84a3ae751f9f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_search_service_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py @@ -1,66 +1,72 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import PipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import SearchServiceClientConfiguration -from ._utils.serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer +from ._configuration import SearchIndexClientConfiguration from .operations import ( + AgentsOperations, AliasesOperations, DataSourcesOperations, IndexersOperations, IndexesOperations, - KnowledgeAgentsOperations, - KnowledgeSourcesOperations, SkillsetsOperations, + SourcesOperations, SynonymMapsOperations, - _SearchServiceClientOperationsMixin, + _SearchIndexClientOperationsMixin, ) +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class SearchServiceClient(_SearchServiceClientOperationsMixin): # pylint: disable=too-many-instance-attributes - """Client that can be used to manage and query indexes and documents, as well as manage other - resources, on a search service. - :ivar knowledge_agents: KnowledgeAgentsOperations operations - :vartype knowledge_agents: azure.search.documents.indexes.operations.KnowledgeAgentsOperations - :ivar knowledge_sources: KnowledgeSourcesOperations operations - :vartype knowledge_sources: - azure.search.documents.indexes.operations.KnowledgeSourcesOperations +class SearchIndexClient(_SearchIndexClientOperationsMixin): # pylint: disable=too-many-instance-attributes + """SearchIndexClient. + :ivar data_sources: DataSourcesOperations operations - :vartype data_sources: azure.search.documents.indexes.operations.DataSourcesOperations + :vartype data_sources: azure.search.documents.operations.DataSourcesOperations :ivar indexers: IndexersOperations operations - :vartype indexers: azure.search.documents.indexes.operations.IndexersOperations + :vartype indexers: azure.search.documents.operations.IndexersOperations :ivar skillsets: SkillsetsOperations operations - :vartype skillsets: azure.search.documents.indexes.operations.SkillsetsOperations + :vartype skillsets: azure.search.documents.operations.SkillsetsOperations :ivar synonym_maps: SynonymMapsOperations operations - :vartype synonym_maps: azure.search.documents.indexes.operations.SynonymMapsOperations + :vartype synonym_maps: azure.search.documents.operations.SynonymMapsOperations :ivar indexes: IndexesOperations operations - :vartype indexes: azure.search.documents.indexes.operations.IndexesOperations + :vartype indexes: azure.search.documents.operations.IndexesOperations :ivar aliases: AliasesOperations operations - :vartype aliases: azure.search.documents.indexes.operations.AliasesOperations - :param endpoint: The endpoint URL of the search service. Required. + :vartype aliases: azure.search.documents.operations.AliasesOperations + :ivar agents: AgentsOperations operations + :vartype agents: azure.search.documents.operations.AgentsOperations + :ivar sources: SourcesOperations operations + :vartype sources: azure.search.documents.operations.SourcesOperations + :param endpoint: Service host. Required. :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = SearchServiceClientConfiguration(endpoint=endpoint, **kwargs) + self._config = SearchIndexClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -81,30 +87,25 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.knowledge_agents = KnowledgeAgentsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.knowledge_sources = KnowledgeSourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) self.data_sources = DataSourcesOperations(self._client, self._config, self._serialize, self._deserialize) self.indexers = IndexersOperations(self._client, self._config, self._serialize, self._deserialize) self.skillsets = SkillsetsOperations(self._client, self._config, self._serialize, self._deserialize) self.synonym_maps = SynonymMapsOperations(self._client, self._config, self._serialize, self._deserialize) self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) self.aliases = AliasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.agents = AgentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.sources = SourcesOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py new file mode 100644 index 000000000000..9993578ced46 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py deleted file mode 100644 index 7b3c14c7b1b6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_service_client import SearchServiceClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchServiceClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py deleted file mode 100644 index e900f7a996e1..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchServiceClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - - self.endpoint = endpoint - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchserviceclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py deleted file mode 100644 index 0d508719ab3c..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/utils.py +++ /dev/null @@ -1,23 +0,0 @@ -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Generic, TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .serialization import Deserializer, Serializer - - -TClient = TypeVar("TClient") -TConfig = TypeVar("TConfig") - - -class ClientMixinABC(ABC, Generic[TClient, TConfig]): - """DO NOT use this class. It is for internal typing use only.""" - - _client: TClient - _config: TConfig - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py deleted file mode 100644 index 7b3c14c7b1b6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._search_service_client import SearchServiceClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "SearchServiceClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py deleted file mode 100644 index ef3305669e7a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -VERSION = "unknown" - - -class SearchServiceClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for SearchServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The endpoint URL of the search service. Required. - :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - - self.endpoint = endpoint - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "searchserviceclient/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py deleted file mode 100644 index ff48959532fe..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_agents_operations import KnowledgeAgentsOperations # type: ignore -from ._knowledge_sources_operations import KnowledgeSourcesOperations # type: ignore -from ._data_sources_operations import DataSourcesOperations # type: ignore -from ._indexers_operations import IndexersOperations # type: ignore -from ._skillsets_operations import SkillsetsOperations # type: ignore -from ._synonym_maps_operations import SynonymMapsOperations # type: ignore -from ._indexes_operations import IndexesOperations # type: ignore -from ._aliases_operations import AliasesOperations # type: ignore -from ._search_service_client_operations import _SearchServiceClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeAgentsOperations", - "KnowledgeSourcesOperations", - "DataSourcesOperations", - "IndexersOperations", - "SkillsetsOperations", - "SynonymMapsOperations", - "IndexesOperations", - "AliasesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py deleted file mode 100644 index 5a865916bad7..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py +++ /dev/null @@ -1,611 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._aliases_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class AliasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`aliases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create( - self, - alias: _models.SearchAlias, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - alias: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - alias: Union[_models.SearchAlias, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Is either a SearchAlias type or a - IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.SearchAlias"]: - """Lists all aliases available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Aliases - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchAlias or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListAliasesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListAliasesResult", pipeline_response) - list_of_elem = deserialized.aliases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: _models.SearchAlias, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: Union[_models.SearchAlias, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Is either a SearchAlias type or - a IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_or_update_request( - alias_name=alias_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - alias_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Alias - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, alias_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchAlias: - """Retrieves an alias definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Alias - - :param alias_name: The name of the alias to retrieve. Required. - :type alias_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py deleted file mode 100644 index 7afca4d03c25..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_data_sources_operations.py +++ /dev/null @@ -1,592 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._data_sources_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class DataSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`data_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: _models.SearchIndexerDataSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_or_update_request( - data_source_name=data_source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - data_source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Data-Source - - :param data_source_name: The name of the datasource to delete. Required. - :type data_source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, data_source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Retrieves a datasource definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Data-Source - - :param data_source_name: The name of the datasource to retrieve. Required. - :type data_source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListDataSourcesResult: - """Lists all datasources available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Data-Sources - - :param select: Selects which top-level properties of the data sources to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListDataSourcesResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListDataSourcesResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListDataSourcesResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - data_source: _models.SearchIndexerDataSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - data_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py deleted file mode 100644 index 322e8ff264c7..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexers_operations.py +++ /dev/null @@ -1,1093 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._indexers_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_get_status_request, - build_list_request, - build_reset_docs_request, - build_reset_request, - build_resync_request, - build_run_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class IndexersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`indexers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def reset( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Resets the change tracking state associated with an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Reset-Indexer - - :param indexer_name: The name of the indexer to reset. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_reset_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[_models.DocumentKeysOrIds] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[Union[_models.DocumentKeysOrIds, IO[bytes]]] = None, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Is either a DocumentKeysOrIds type or a IO[bytes] type. Default value is - None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if keys_or_ids else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" if keys_or_ids else None - _json = None - _content = None - if isinstance(keys_or_ids, (IOBase, bytes)): - _content = keys_or_ids - else: - if keys_or_ids is not None: - _json = self._serialize.body(keys_or_ids, "DocumentKeysOrIds") - else: - _json = None - - _request = build_reset_docs_request( - indexer_name=indexer_name, - overwrite=overwrite, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def resync( - self, - indexer_name: str, - indexer_resync: _models.IndexerResyncBody, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def resync( - self, - indexer_name: str, - indexer_resync: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def resync( - self, - indexer_name: str, - indexer_resync: Union[_models.IndexerResyncBody, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Is either a IndexerResyncBody type or a IO[bytes] type. Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer_resync, (IOBase, bytes)): - _content = indexer_resync - else: - _json = self._serialize.body(indexer_resync, "IndexerResyncBody") - - _request = build_resync_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def run( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Runs an indexer on-demand. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Run-Indexer - - :param indexer_name: The name of the indexer to run. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_run_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: _models.SearchIndexer, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: Union[_models.SearchIndexer, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Is either a SearchIndexer - type or a IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_or_update_request( - indexer_name=indexer_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - indexer_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Indexer - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexer: - """Retrieves an indexer definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer - - :param indexer_name: The name of the indexer to retrieve. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListIndexersResult: - """Lists all indexers available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexers - - :param select: Selects which top-level properties of the indexers to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListIndexersResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexersResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListIndexersResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - indexer: _models.SearchIndexer, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - indexer: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - indexer: Union[_models.SearchIndexer, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Is either a SearchIndexer type or a - IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_status( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerStatus: - """Returns the current status and execution history of an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer-Status - - :param indexer_name: The name of the indexer for which to retrieve status. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerStatus or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerStatus] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_status_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py deleted file mode 100644 index 4ae89238f423..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_indexes_operations.py +++ /dev/null @@ -1,849 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._indexes_operations import ( - build_analyze_request, - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_get_statistics_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`indexes` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create( - self, - index: _models.SearchIndex, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - index: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - index: Union[_models.SearchIndex, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Is either a SearchIndex type or a - IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.SearchIndex"]: - """Lists all indexes available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexes - - :param select: Selects which top-level properties of the index definitions to retrieve. - Specified as a comma-separated list of JSON property names, or '*' for all properties. The - default is all properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchIndex or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexesResult", pipeline_response) - list_of_elem = deserialized.indexes - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: _models.SearchIndex, - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: IO[bytes], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: Union[_models.SearchIndex, IO[bytes]], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Is either a SearchIndex type or - a IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_or_update_request( - index_name=index_name, - prefer=prefer, - allow_index_downtime=allow_index_downtime, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - index_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. This operation is permanent, with no - recovery option. Make sure you have a master copy of your index definition, data ingestion - code, and a backup of the primary data source in case you need to re-build the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Index - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndex: - """Retrieves an index definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index - - :param index_name: The name of the index to retrieve. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_statistics( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.GetIndexStatisticsResult: - """Returns statistics for the given index, including a document count and storage usage. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index-Statistics - - :param index_name: The name of the index for which to retrieve statistics. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: GetIndexStatisticsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GetIndexStatisticsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_statistics_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("GetIndexStatisticsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def analyze( - self, - index_name: str, - request: _models.AnalyzeRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def analyze( - self, - index_name: str, - request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def analyze( - self, - index_name: str, - request: Union[_models.AnalyzeRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Is either a - AnalyzeRequest type or a IO[bytes] type. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AnalyzeResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(request, (IOBase, bytes)): - _content = request - else: - _json = self._serialize.body(request, "AnalyzeRequest") - - _request = build_analyze_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AnalyzeResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_agents_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_agents_operations.py deleted file mode 100644 index 9f6db1526f1b..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_agents_operations.py +++ /dev/null @@ -1,583 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._knowledge_agents_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class KnowledgeAgentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`knowledge_agents` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - agent_name: str, - prefer: Union[str, _models.Enum0], - knowledge_agent: _models.KnowledgeAgent, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent to create or update. Required. - :type agent_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - agent_name: str, - prefer: Union[str, _models.Enum0], - knowledge_agent: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent to create or update. Required. - :type agent_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - agent_name: str, - prefer: Union[str, _models.Enum0], - knowledge_agent: Union[_models.KnowledgeAgent, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent to create or update. Required. - :type agent_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_agent: The definition of the agent to create or update. Is either a - KnowledgeAgent type or a IO[bytes] type. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeAgent] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent - else: - _json = self._serialize.body(knowledge_agent, "KnowledgeAgent") - - _request = build_create_or_update_request( - agent_name=agent_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgent", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - agent_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing agent. - - :param agent_name: The name of the agent to delete. Required. - :type agent_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - agent_name=agent_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, agent_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeAgent: - """Retrieves an agent definition. - - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeAgent] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - agent_name=agent_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgent", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.KnowledgeAgent"]: - """Lists all agents available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeAgent or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeAgentsResult", pipeline_response) - list_of_elem = deserialized.knowledge_agents - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create( - self, - knowledge_agent: _models.KnowledgeAgent, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - knowledge_agent: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - knowledge_agent: Union[_models.KnowledgeAgent, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Is either a KnowledgeAgent type - or a IO[bytes] type. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeAgent] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent - else: - _json = self._serialize.body(knowledge_agent, "KnowledgeAgent") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgent", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py deleted file mode 100644 index 7ffab10d66d4..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_knowledge_sources_operations.py +++ /dev/null @@ -1,583 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._knowledge_sources_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class KnowledgeSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`knowledge_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: _models.KnowledgeSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Is either - a KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_or_update_request( - source_name=source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeSource: - """Retrieves a knowledge source definition. - - :param source_name: The name of the knowledge source to retrieve. Required. - :type source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.KnowledgeSource"]: - """Lists all knowledge sources available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeSource or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeSourcesResult", pipeline_response) - list_of_elem = deserialized.knowledge_sources - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @overload - async def create( - self, - knowledge_source: _models.KnowledgeSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - knowledge_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Is either a - KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py deleted file mode 100644 index 3fc8641520c8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_search_service_client_operations.py +++ /dev/null @@ -1,195 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.utils import ClientMixinABC -from ...operations._search_service_client_operations import ( - build_get_index_stats_summary_request, - build_get_service_statistics_request, -) -from .._configuration import SearchServiceClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _SearchServiceClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchServiceClientConfiguration] -): - - @distributed_trace_async - async def get_service_statistics( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchServiceStatistics: - """Gets service level statistics for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchServiceStatistics or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchServiceStatistics] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_service_statistics_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchServiceStatistics", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_index_stats_summary( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.IndexStatisticsSummary"]: - """Retrieves a summary of statistics for all indexes in the search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either IndexStatisticsSummary or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexStatsSummary] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_index_stats_summary_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexStatsSummary", pipeline_response) - list_of_elem = deserialized.indexes_statistics - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py deleted file mode 100644 index eabcb91378bf..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_skillsets_operations.py +++ /dev/null @@ -1,748 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._skillsets_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, - build_reset_skills_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class SkillsetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`skillsets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: _models.SearchIndexerSkillset, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Is either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_or_update_request( - skillset_name=skillset_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - skillset_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/delete-skillset - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, skillset_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Retrieves a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/get-skillset - - :param skillset_name: The name of the skillset to retrieve. Required. - :type skillset_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSkillsetsResult: - """List all skillsets in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/list-skillset - - :param select: Selects which top-level properties of the skillsets to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSkillsetsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSkillsetsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSkillsetsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - skillset: _models.SearchIndexerSkillset, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - skillset: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. Is - either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def reset_skills( - self, - skillset_name: str, - skill_names: _models.SkillNames, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def reset_skills( - self, - skillset_name: str, - skill_names: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def reset_skills( - self, - skillset_name: str, - skill_names: Union[_models.SkillNames, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Is either a SkillNames type or a IO[bytes] - type. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skill_names, (IOBase, bytes)): - _content = skill_names - else: - _json = self._serialize.body(skill_names, "SkillNames") - - _request = build_reset_skills_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py deleted file mode 100644 index c226c1d06f96..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py +++ /dev/null @@ -1,579 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._synonym_maps_operations import ( - build_create_or_update_request, - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) -from .._configuration import SearchServiceClientConfiguration - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class SynonymMapsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.aio.SearchServiceClient`'s - :attr:`synonym_maps` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: _models.SynonymMap, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: Union[_models.SynonymMap, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Is either a - SynonymMap type or a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_or_update_request( - synonym_map_name=synonym_map_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, - synonym_map_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Synonym-Map - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, synonym_map_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SynonymMap: - """Retrieves a synonym map definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Synonym-Map - - :param synonym_map_name: The name of the synonym map to retrieve. Required. - :type synonym_map_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSynonymMapsResult: - """Lists all synonym maps available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Synonym-Maps - - :param select: Selects which top-level properties of the synonym maps to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSynonymMapsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSynonymMapsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSynonymMapsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, - synonym_map: _models.SynonymMap, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - synonym_map: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - synonym_map: Union[_models.SynonymMap, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Is either a SynonymMap type or - a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py deleted file mode 100644 index a376f02c866a..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py +++ /dev/null @@ -1,586 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models_py3 import ( # type: ignore - AIServicesAccountIdentity, - AIServicesAccountKey, - AIServicesVisionParameters, - AIServicesVisionVectorizer, - AnalyzeRequest, - AnalyzeResult, - AnalyzedTokenInfo, - AsciiFoldingTokenFilter, - AzureActiveDirectoryApplicationCredentials, - AzureBlobKnowledgeSource, - AzureBlobKnowledgeSourceParameters, - AzureMachineLearningParameters, - AzureMachineLearningSkill, - AzureMachineLearningVectorizer, - AzureOpenAIEmbeddingSkill, - AzureOpenAITokenizerParameters, - AzureOpenAIVectorizer, - AzureOpenAIVectorizerParameters, - BM25SimilarityAlgorithm, - BinaryQuantizationCompression, - CharFilter, - ChatCompletionResponseFormat, - ChatCompletionResponseFormatJsonSchemaProperties, - ChatCompletionSchema, - ChatCompletionSkill, - CjkBigramTokenFilter, - ClassicSimilarityAlgorithm, - ClassicTokenizer, - CognitiveServicesAccount, - CognitiveServicesAccountKey, - CommonGramTokenFilter, - CommonModelParameters, - ConditionalSkill, - CorsOptions, - CustomAnalyzer, - CustomEntity, - CustomEntityAlias, - CustomEntityLookupSkill, - CustomNormalizer, - DataChangeDetectionPolicy, - DataDeletionDetectionPolicy, - DataSourceCredentials, - DefaultCognitiveServicesAccount, - DictionaryDecompounderTokenFilter, - DistanceScoringFunction, - DistanceScoringParameters, - DocumentExtractionSkill, - DocumentIntelligenceLayoutSkill, - DocumentIntelligenceLayoutSkillChunkingProperties, - DocumentKeysOrIds, - EdgeNGramTokenFilter, - EdgeNGramTokenFilterV2, - EdgeNGramTokenizer, - ElisionTokenFilter, - EntityLinkingSkill, - EntityRecognitionSkill, - EntityRecognitionSkillV3, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, - ExhaustiveKnnAlgorithmConfiguration, - ExhaustiveKnnParameters, - FieldMapping, - FieldMappingFunction, - FreshnessScoringFunction, - FreshnessScoringParameters, - GetIndexStatisticsResult, - HighWaterMarkChangeDetectionPolicy, - HnswAlgorithmConfiguration, - HnswParameters, - ImageAnalysisSkill, - IndexStatisticsSummary, - IndexerCurrentState, - IndexerExecutionResult, - IndexerResyncBody, - IndexingParameters, - IndexingParametersConfiguration, - IndexingSchedule, - InputFieldMappingEntry, - KeepTokenFilter, - KeyPhraseExtractionSkill, - KeywordMarkerTokenFilter, - KeywordTokenizer, - KeywordTokenizerV2, - KnowledgeAgent, - KnowledgeAgentAzureOpenAIModel, - KnowledgeAgentModel, - KnowledgeAgentOutputConfiguration, - KnowledgeAgentRequestLimits, - KnowledgeSource, - KnowledgeSourceReference, - LanguageDetectionSkill, - LengthTokenFilter, - LexicalAnalyzer, - LexicalNormalizer, - LexicalTokenizer, - LimitTokenFilter, - ListAliasesResult, - ListDataSourcesResult, - ListIndexStatsSummary, - ListIndexersResult, - ListIndexesResult, - ListKnowledgeAgentsResult, - ListKnowledgeSourcesResult, - ListSkillsetsResult, - ListSynonymMapsResult, - LuceneStandardAnalyzer, - LuceneStandardTokenizer, - LuceneStandardTokenizerV2, - MagnitudeScoringFunction, - MagnitudeScoringParameters, - MappingCharFilter, - MergeSkill, - MicrosoftLanguageStemmingTokenizer, - MicrosoftLanguageTokenizer, - NGramTokenFilter, - NGramTokenFilterV2, - NGramTokenizer, - NativeBlobSoftDeleteDeletionDetectionPolicy, - OcrSkill, - OutputFieldMappingEntry, - PIIDetectionSkill, - PathHierarchyTokenizerV2, - PatternAnalyzer, - PatternCaptureTokenFilter, - PatternReplaceCharFilter, - PatternReplaceTokenFilter, - PatternTokenizer, - PhoneticTokenFilter, - RequestOptions, - RescoringOptions, - ResourceCounter, - ScalarQuantizationCompression, - ScalarQuantizationParameters, - ScoringFunction, - ScoringProfile, - SearchAlias, - SearchField, - SearchIndex, - SearchIndexKnowledgeSource, - SearchIndexKnowledgeSourceParameters, - SearchIndexer, - SearchIndexerCache, - SearchIndexerDataContainer, - SearchIndexerDataIdentity, - SearchIndexerDataNoneIdentity, - SearchIndexerDataSource, - SearchIndexerDataUserAssignedIdentity, - SearchIndexerError, - SearchIndexerIndexProjection, - SearchIndexerIndexProjectionSelector, - SearchIndexerIndexProjectionsParameters, - SearchIndexerKnowledgeStore, - SearchIndexerKnowledgeStoreBlobProjectionSelector, - SearchIndexerKnowledgeStoreFileProjectionSelector, - SearchIndexerKnowledgeStoreObjectProjectionSelector, - SearchIndexerKnowledgeStoreParameters, - SearchIndexerKnowledgeStoreProjection, - SearchIndexerKnowledgeStoreProjectionSelector, - SearchIndexerKnowledgeStoreTableProjectionSelector, - SearchIndexerLimits, - SearchIndexerSkill, - SearchIndexerSkillset, - SearchIndexerStatus, - SearchIndexerWarning, - SearchResourceEncryptionKey, - SearchServiceCounters, - SearchServiceLimits, - SearchServiceStatistics, - SearchSuggester, - SemanticConfiguration, - SemanticField, - SemanticPrioritizedFields, - SemanticSearch, - SentimentSkill, - SentimentSkillV3, - ShaperSkill, - ShingleTokenFilter, - SimilarityAlgorithm, - SkillNames, - SnowballTokenFilter, - SoftDeleteColumnDeletionDetectionPolicy, - SplitSkill, - SqlIntegratedChangeTrackingPolicy, - StemmerOverrideTokenFilter, - StemmerTokenFilter, - StopAnalyzer, - StopwordsTokenFilter, - SynonymMap, - SynonymTokenFilter, - TagScoringFunction, - TagScoringParameters, - TextTranslationSkill, - TextWeights, - TokenFilter, - TruncateTokenFilter, - UaxUrlEmailTokenizer, - UniqueTokenFilter, - VectorSearch, - VectorSearchAlgorithmConfiguration, - VectorSearchCompression, - VectorSearchProfile, - VectorSearchVectorizer, - VisionVectorizeSkill, - WebApiSkill, - WebApiVectorizer, - WebApiVectorizerParameters, - WordDelimiterTokenFilter, -) - -from ._search_service_client_enums import ( # type: ignore - AIFoundryModelCatalogName, - AzureOpenAIModelName, - BlobIndexerDataToExtract, - BlobIndexerImageAction, - BlobIndexerPDFTextRotationAlgorithm, - BlobIndexerParsingMode, - CharFilterName, - ChatCompletionExtraParametersBehavior, - ChatCompletionResponseFormatType, - CjkBigramTokenFilterScripts, - CustomEntityLookupSkillLanguage, - DocumentIntelligenceLayoutSkillChunkingUnit, - DocumentIntelligenceLayoutSkillExtractionOptions, - DocumentIntelligenceLayoutSkillMarkdownHeaderDepth, - DocumentIntelligenceLayoutSkillOutputFormat, - DocumentIntelligenceLayoutSkillOutputMode, - EdgeNGramTokenFilterSide, - EntityCategory, - EntityRecognitionSkillLanguage, - Enum0, - ImageAnalysisSkillLanguage, - ImageDetail, - IndexProjectionMode, - IndexerExecutionEnvironment, - IndexerExecutionStatus, - IndexerExecutionStatusDetail, - IndexerPermissionOption, - IndexerResyncOption, - IndexerStatus, - IndexingMode, - KeyPhraseExtractionSkillLanguage, - KnowledgeAgentModelKind, - KnowledgeAgentOutputConfigurationModality, - KnowledgeSourceKind, - LexicalAnalyzerName, - LexicalNormalizerName, - LexicalTokenizerName, - MarkdownHeaderDepth, - MarkdownParsingSubmode, - MicrosoftStemmingTokenizerLanguage, - MicrosoftTokenizerLanguage, - OcrLineEnding, - OcrSkillLanguage, - PIIDetectionSkillMaskingMode, - PermissionFilter, - PhoneticEncoder, - RankingOrder, - RegexFlags, - ScoringFunctionAggregation, - ScoringFunctionInterpolation, - SearchFieldDataType, - SearchIndexPermissionFilterOption, - SearchIndexerDataSourceType, - SentimentSkillLanguage, - SnowballTokenFilterLanguage, - SplitSkillEncoderModelName, - SplitSkillLanguage, - SplitSkillUnit, - StemmerTokenFilterLanguage, - StopwordsList, - TextSplitMode, - TextTranslationSkillLanguage, - TokenCharacterKind, - TokenFilterName, - VectorEncodingFormat, - VectorSearchAlgorithmKind, - VectorSearchAlgorithmMetric, - VectorSearchCompressionKind, - VectorSearchCompressionRescoreStorageMethod, - VectorSearchCompressionTarget, - VectorSearchVectorizerKind, - VisualFeature, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AIServicesAccountIdentity", - "AIServicesAccountKey", - "AIServicesVisionParameters", - "AIServicesVisionVectorizer", - "AnalyzeRequest", - "AnalyzeResult", - "AnalyzedTokenInfo", - "AsciiFoldingTokenFilter", - "AzureActiveDirectoryApplicationCredentials", - "AzureBlobKnowledgeSource", - "AzureBlobKnowledgeSourceParameters", - "AzureMachineLearningParameters", - "AzureMachineLearningSkill", - "AzureMachineLearningVectorizer", - "AzureOpenAIEmbeddingSkill", - "AzureOpenAITokenizerParameters", - "AzureOpenAIVectorizer", - "AzureOpenAIVectorizerParameters", - "BM25SimilarityAlgorithm", - "BinaryQuantizationCompression", - "CharFilter", - "ChatCompletionResponseFormat", - "ChatCompletionResponseFormatJsonSchemaProperties", - "ChatCompletionSchema", - "ChatCompletionSkill", - "CjkBigramTokenFilter", - "ClassicSimilarityAlgorithm", - "ClassicTokenizer", - "CognitiveServicesAccount", - "CognitiveServicesAccountKey", - "CommonGramTokenFilter", - "CommonModelParameters", - "ConditionalSkill", - "CorsOptions", - "CustomAnalyzer", - "CustomEntity", - "CustomEntityAlias", - "CustomEntityLookupSkill", - "CustomNormalizer", - "DataChangeDetectionPolicy", - "DataDeletionDetectionPolicy", - "DataSourceCredentials", - "DefaultCognitiveServicesAccount", - "DictionaryDecompounderTokenFilter", - "DistanceScoringFunction", - "DistanceScoringParameters", - "DocumentExtractionSkill", - "DocumentIntelligenceLayoutSkill", - "DocumentIntelligenceLayoutSkillChunkingProperties", - "DocumentKeysOrIds", - "EdgeNGramTokenFilter", - "EdgeNGramTokenFilterV2", - "EdgeNGramTokenizer", - "ElisionTokenFilter", - "EntityLinkingSkill", - "EntityRecognitionSkill", - "EntityRecognitionSkillV3", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "ExhaustiveKnnAlgorithmConfiguration", - "ExhaustiveKnnParameters", - "FieldMapping", - "FieldMappingFunction", - "FreshnessScoringFunction", - "FreshnessScoringParameters", - "GetIndexStatisticsResult", - "HighWaterMarkChangeDetectionPolicy", - "HnswAlgorithmConfiguration", - "HnswParameters", - "ImageAnalysisSkill", - "IndexStatisticsSummary", - "IndexerCurrentState", - "IndexerExecutionResult", - "IndexerResyncBody", - "IndexingParameters", - "IndexingParametersConfiguration", - "IndexingSchedule", - "InputFieldMappingEntry", - "KeepTokenFilter", - "KeyPhraseExtractionSkill", - "KeywordMarkerTokenFilter", - "KeywordTokenizer", - "KeywordTokenizerV2", - "KnowledgeAgent", - "KnowledgeAgentAzureOpenAIModel", - "KnowledgeAgentModel", - "KnowledgeAgentOutputConfiguration", - "KnowledgeAgentRequestLimits", - "KnowledgeSource", - "KnowledgeSourceReference", - "LanguageDetectionSkill", - "LengthTokenFilter", - "LexicalAnalyzer", - "LexicalNormalizer", - "LexicalTokenizer", - "LimitTokenFilter", - "ListAliasesResult", - "ListDataSourcesResult", - "ListIndexStatsSummary", - "ListIndexersResult", - "ListIndexesResult", - "ListKnowledgeAgentsResult", - "ListKnowledgeSourcesResult", - "ListSkillsetsResult", - "ListSynonymMapsResult", - "LuceneStandardAnalyzer", - "LuceneStandardTokenizer", - "LuceneStandardTokenizerV2", - "MagnitudeScoringFunction", - "MagnitudeScoringParameters", - "MappingCharFilter", - "MergeSkill", - "MicrosoftLanguageStemmingTokenizer", - "MicrosoftLanguageTokenizer", - "NGramTokenFilter", - "NGramTokenFilterV2", - "NGramTokenizer", - "NativeBlobSoftDeleteDeletionDetectionPolicy", - "OcrSkill", - "OutputFieldMappingEntry", - "PIIDetectionSkill", - "PathHierarchyTokenizerV2", - "PatternAnalyzer", - "PatternCaptureTokenFilter", - "PatternReplaceCharFilter", - "PatternReplaceTokenFilter", - "PatternTokenizer", - "PhoneticTokenFilter", - "RequestOptions", - "RescoringOptions", - "ResourceCounter", - "ScalarQuantizationCompression", - "ScalarQuantizationParameters", - "ScoringFunction", - "ScoringProfile", - "SearchAlias", - "SearchField", - "SearchIndex", - "SearchIndexKnowledgeSource", - "SearchIndexKnowledgeSourceParameters", - "SearchIndexer", - "SearchIndexerCache", - "SearchIndexerDataContainer", - "SearchIndexerDataIdentity", - "SearchIndexerDataNoneIdentity", - "SearchIndexerDataSource", - "SearchIndexerDataUserAssignedIdentity", - "SearchIndexerError", - "SearchIndexerIndexProjection", - "SearchIndexerIndexProjectionSelector", - "SearchIndexerIndexProjectionsParameters", - "SearchIndexerKnowledgeStore", - "SearchIndexerKnowledgeStoreBlobProjectionSelector", - "SearchIndexerKnowledgeStoreFileProjectionSelector", - "SearchIndexerKnowledgeStoreObjectProjectionSelector", - "SearchIndexerKnowledgeStoreParameters", - "SearchIndexerKnowledgeStoreProjection", - "SearchIndexerKnowledgeStoreProjectionSelector", - "SearchIndexerKnowledgeStoreTableProjectionSelector", - "SearchIndexerLimits", - "SearchIndexerSkill", - "SearchIndexerSkillset", - "SearchIndexerStatus", - "SearchIndexerWarning", - "SearchResourceEncryptionKey", - "SearchServiceCounters", - "SearchServiceLimits", - "SearchServiceStatistics", - "SearchSuggester", - "SemanticConfiguration", - "SemanticField", - "SemanticPrioritizedFields", - "SemanticSearch", - "SentimentSkill", - "SentimentSkillV3", - "ShaperSkill", - "ShingleTokenFilter", - "SimilarityAlgorithm", - "SkillNames", - "SnowballTokenFilter", - "SoftDeleteColumnDeletionDetectionPolicy", - "SplitSkill", - "SqlIntegratedChangeTrackingPolicy", - "StemmerOverrideTokenFilter", - "StemmerTokenFilter", - "StopAnalyzer", - "StopwordsTokenFilter", - "SynonymMap", - "SynonymTokenFilter", - "TagScoringFunction", - "TagScoringParameters", - "TextTranslationSkill", - "TextWeights", - "TokenFilter", - "TruncateTokenFilter", - "UaxUrlEmailTokenizer", - "UniqueTokenFilter", - "VectorSearch", - "VectorSearchAlgorithmConfiguration", - "VectorSearchCompression", - "VectorSearchProfile", - "VectorSearchVectorizer", - "VisionVectorizeSkill", - "WebApiSkill", - "WebApiVectorizer", - "WebApiVectorizerParameters", - "WordDelimiterTokenFilter", - "AIFoundryModelCatalogName", - "AzureOpenAIModelName", - "BlobIndexerDataToExtract", - "BlobIndexerImageAction", - "BlobIndexerPDFTextRotationAlgorithm", - "BlobIndexerParsingMode", - "CharFilterName", - "ChatCompletionExtraParametersBehavior", - "ChatCompletionResponseFormatType", - "CjkBigramTokenFilterScripts", - "CustomEntityLookupSkillLanguage", - "DocumentIntelligenceLayoutSkillChunkingUnit", - "DocumentIntelligenceLayoutSkillExtractionOptions", - "DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", - "DocumentIntelligenceLayoutSkillOutputFormat", - "DocumentIntelligenceLayoutSkillOutputMode", - "EdgeNGramTokenFilterSide", - "EntityCategory", - "EntityRecognitionSkillLanguage", - "Enum0", - "ImageAnalysisSkillLanguage", - "ImageDetail", - "IndexProjectionMode", - "IndexerExecutionEnvironment", - "IndexerExecutionStatus", - "IndexerExecutionStatusDetail", - "IndexerPermissionOption", - "IndexerResyncOption", - "IndexerStatus", - "IndexingMode", - "KeyPhraseExtractionSkillLanguage", - "KnowledgeAgentModelKind", - "KnowledgeAgentOutputConfigurationModality", - "KnowledgeSourceKind", - "LexicalAnalyzerName", - "LexicalNormalizerName", - "LexicalTokenizerName", - "MarkdownHeaderDepth", - "MarkdownParsingSubmode", - "MicrosoftStemmingTokenizerLanguage", - "MicrosoftTokenizerLanguage", - "OcrLineEnding", - "OcrSkillLanguage", - "PIIDetectionSkillMaskingMode", - "PermissionFilter", - "PhoneticEncoder", - "RankingOrder", - "RegexFlags", - "ScoringFunctionAggregation", - "ScoringFunctionInterpolation", - "SearchFieldDataType", - "SearchIndexPermissionFilterOption", - "SearchIndexerDataSourceType", - "SentimentSkillLanguage", - "SnowballTokenFilterLanguage", - "SplitSkillEncoderModelName", - "SplitSkillLanguage", - "SplitSkillUnit", - "StemmerTokenFilterLanguage", - "StopwordsList", - "TextSplitMode", - "TextTranslationSkillLanguage", - "TokenCharacterKind", - "TokenFilterName", - "VectorEncodingFormat", - "VectorSearchAlgorithmKind", - "VectorSearchAlgorithmMetric", - "VectorSearchCompressionKind", - "VectorSearchCompressionRescoreStorageMethod", - "VectorSearchCompressionTarget", - "VectorSearchVectorizerKind", - "VisualFeature", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py deleted file mode 100644 index fb0e8ee558b2..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_models_py3.py +++ /dev/null @@ -1,13171 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union, MutableMapping - -from .._utils import serialization as _serialization - -JSON = MutableMapping[str, Any] - -if TYPE_CHECKING: - from .. import models as _models - - -class CognitiveServicesAccount(_serialization.Model): - """Base type for describing any Azure AI service resource attached to a skillset. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AIServicesAccountIdentity, AIServicesAccountKey, CognitiveServicesAccountKey, - DefaultCognitiveServicesAccount - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.AIServicesByIdentity": "AIServicesAccountIdentity", - "#Microsoft.Azure.Search.AIServicesByKey": "AIServicesAccountKey", - "#Microsoft.Azure.Search.CognitiveServicesByKey": "CognitiveServicesAccountKey", - "#Microsoft.Azure.Search.DefaultCognitiveServices": "DefaultCognitiveServicesAccount", - } - } - - def __init__(self, *, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.description = description - - -class AIServicesAccountIdentity(CognitiveServicesAccount): - """The multi-region account of an Azure AI service resource that's attached to a skillset. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - :ivar identity: The user-assigned managed identity used for connections to AI Service. If not - specified, the system-assigned managed identity is used. On updates to the skillset, if the - identity is unspecified, the value remains unchanged. If set to "none", the value of this - property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. - :vartype subdomain_url: str - """ - - _validation = { - "odata_type": {"required": True}, - "subdomain_url": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "subdomain_url": {"key": "subdomainUrl", "type": "str"}, - } - - def __init__( - self, - *, - subdomain_url: str, - description: Optional[str] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - :keyword identity: The user-assigned managed identity used for connections to AI Service. If - not specified, the system-assigned managed identity is used. On updates to the skillset, if the - identity is unspecified, the value remains unchanged. If set to "none", the value of this - property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword subdomain_url: The subdomain url for the corresponding AI Service. Required. - :paramtype subdomain_url: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.AIServicesByIdentity" - self.identity = identity - self.subdomain_url = subdomain_url - - -class AIServicesAccountKey(CognitiveServicesAccount): - """The account key of an Azure AI service resource that's attached to a skillset, to be used with - the resource's subdomain. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - :ivar key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :vartype key: str - :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. - :vartype subdomain_url: str - """ - - _validation = { - "odata_type": {"required": True}, - "key": {"required": True}, - "subdomain_url": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "key": {"key": "key", "type": "str"}, - "subdomain_url": {"key": "subdomainUrl", "type": "str"}, - } - - def __init__(self, *, key: str, subdomain_url: str, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - :keyword key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :paramtype key: str - :keyword subdomain_url: The subdomain url for the corresponding AI Service. Required. - :paramtype subdomain_url: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.AIServicesByKey" - self.key = key - self.subdomain_url = subdomain_url - - -class AIServicesVisionParameters(_serialization.Model): - """Specifies the AI Services Vision parameters for vectorizing a query image or text. - - All required parameters must be populated in order to send to server. - - :ivar model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :vartype model_version: str - :ivar resource_uri: The resource URI of the AI Services resource. Required. - :vartype resource_uri: str - :ivar api_key: API key of the designated AI Services resource. - :vartype api_key: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the index, if the identity is unspecified, the value remains unchanged. If - set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _validation = { - "model_version": {"required": True}, - "resource_uri": {"required": True}, - } - - _attribute_map = { - "model_version": {"key": "modelVersion", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - model_version: str, - resource_uri: str, - api_key: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :paramtype model_version: str - :keyword resource_uri: The resource URI of the AI Services resource. Required. - :paramtype resource_uri: str - :keyword api_key: API key of the designated AI Services resource. - :paramtype api_key: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the index, if the identity is unspecified, the value remains unchanged. If - set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.model_version = model_version - self.resource_uri = resource_uri - self.api_key = api_key - self.auth_identity = auth_identity - - -class VectorSearchVectorizer(_serialization.Model): - """Specifies the vectorization method to be used during query time. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AIServicesVisionVectorizer, AzureMachineLearningVectorizer, AzureOpenAIVectorizer, - WebApiVectorizer - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": { - "aiServicesVision": "AIServicesVisionVectorizer", - "aml": "AzureMachineLearningVectorizer", - "azureOpenAI": "AzureOpenAIVectorizer", - "customWebApi": "WebApiVectorizer", - } - } - - def __init__(self, *, vectorizer_name: str, **kwargs: Any) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - """ - super().__init__(**kwargs) - self.vectorizer_name = vectorizer_name - self.kind: Optional[str] = None - - -class AIServicesVisionVectorizer(VectorSearchVectorizer): - """Specifies the AI Services Vision parameters for vectorizing a query image or text. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar ai_services_vision_parameters: Contains the parameters specific to AI Services Vision - embedding vectorization. - :vartype ai_services_vision_parameters: - ~azure.search.documents.indexes.models.AIServicesVisionParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "ai_services_vision_parameters": {"key": "aiServicesVisionParameters", "type": "AIServicesVisionParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - ai_services_vision_parameters: Optional["_models.AIServicesVisionParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword ai_services_vision_parameters: Contains the parameters specific to AI Services Vision - embedding vectorization. - :paramtype ai_services_vision_parameters: - ~azure.search.documents.indexes.models.AIServicesVisionParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "aiServicesVision" - self.ai_services_vision_parameters = ai_services_vision_parameters - - -class AnalyzedTokenInfo(_serialization.Model): - """Information about a token returned by an analyzer. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar token: The token returned by the analyzer. Required. - :vartype token: str - :ivar start_offset: The index of the first character of the token in the input text. Required. - :vartype start_offset: int - :ivar end_offset: The index of the last character of the token in the input text. Required. - :vartype end_offset: int - :ivar position: The position of the token in the input text relative to other tokens. The first - token in the input text has position 0, the next has position 1, and so on. Depending on the - analyzer used, some tokens might have the same position, for example if they are synonyms of - each other. Required. - :vartype position: int - """ - - _validation = { - "token": {"required": True, "readonly": True}, - "start_offset": {"required": True, "readonly": True}, - "end_offset": {"required": True, "readonly": True}, - "position": {"required": True, "readonly": True}, - } - - _attribute_map = { - "token": {"key": "token", "type": "str"}, - "start_offset": {"key": "startOffset", "type": "int"}, - "end_offset": {"key": "endOffset", "type": "int"}, - "position": {"key": "position", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.token: Optional[str] = None - self.start_offset: Optional[int] = None - self.end_offset: Optional[int] = None - self.position: Optional[int] = None - - -class AnalyzeRequest(_serialization.Model): - """Specifies some text and analysis components used to break that text into tokens. - - All required parameters must be populated in order to send to server. - - :ivar text: The text to break into tokens. Required. - :vartype text: str - :ivar analyzer: The name of the analyzer to use to break the given text. If this parameter is - not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are - mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar tokenizer: The name of the tokenizer to use to break the given text. If this parameter is - not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters are - mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", "letter", - "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", - "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". - :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar normalizer: The name of the normalizer to use to normalize the given text. Known values - are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :ivar token_filters: An optional list of token filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: An optional list of character filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - - _validation = { - "text": {"required": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "str"}, - "analyzer": {"key": "analyzer", "type": "str"}, - "tokenizer": {"key": "tokenizer", "type": "str"}, - "normalizer": {"key": "normalizer", "type": "str"}, - "token_filters": {"key": "tokenFilters", "type": "[str]"}, - "char_filters": {"key": "charFilters", "type": "[str]"}, - } - - def __init__( - self, - *, - text: str, - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - tokenizer: Optional[Union[str, "_models.LexicalTokenizerName"]] = None, - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, - token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, - char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword text: The text to break into tokens. Required. - :paramtype text: str - :keyword analyzer: The name of the analyzer to use to break the given text. If this parameter - is not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters - are mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", - "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", - "zh-Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", - "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", - "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", - "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", - "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", - "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", - "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", - "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", - "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", - "pt-PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", - "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", - "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", - "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", - "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", - "simple", "stop", and "whitespace". - :paramtype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword tokenizer: The name of the tokenizer to use to break the given text. If this parameter - is not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters - are mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", "letter", - "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", - "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". - :paramtype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :keyword normalizer: The name of the normalizer to use to normalize the given text. Known - values are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :paramtype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :keyword token_filters: An optional list of token filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :paramtype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: An optional list of character filters to use when breaking the given - text. This parameter can only be set when using the tokenizer parameter. - :paramtype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - super().__init__(**kwargs) - self.text = text - self.analyzer = analyzer - self.tokenizer = tokenizer - self.normalizer = normalizer - self.token_filters = token_filters - self.char_filters = char_filters - - -class AnalyzeResult(_serialization.Model): - """The result of testing an analyzer on text. - - All required parameters must be populated in order to send to server. - - :ivar tokens: The list of tokens returned by the analyzer specified in the request. Required. - :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] - """ - - _validation = { - "tokens": {"required": True}, - } - - _attribute_map = { - "tokens": {"key": "tokens", "type": "[AnalyzedTokenInfo]"}, - } - - def __init__(self, *, tokens: list["_models.AnalyzedTokenInfo"], **kwargs: Any) -> None: - """ - :keyword tokens: The list of tokens returned by the analyzer specified in the request. - Required. - :paramtype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] - """ - super().__init__(**kwargs) - self.tokens = tokens - - -class TokenFilter(_serialization.Model): - """Base type for token filters. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AsciiFoldingTokenFilter, CjkBigramTokenFilter, CommonGramTokenFilter, - DictionaryDecompounderTokenFilter, EdgeNGramTokenFilter, EdgeNGramTokenFilterV2, - ElisionTokenFilter, KeepTokenFilter, KeywordMarkerTokenFilter, LengthTokenFilter, - LimitTokenFilter, NGramTokenFilter, NGramTokenFilterV2, PatternCaptureTokenFilter, - PatternReplaceTokenFilter, PhoneticTokenFilter, ShingleTokenFilter, SnowballTokenFilter, - StemmerOverrideTokenFilter, StemmerTokenFilter, StopwordsTokenFilter, SynonymTokenFilter, - TruncateTokenFilter, UniqueTokenFilter, WordDelimiterTokenFilter - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.AsciiFoldingTokenFilter": "AsciiFoldingTokenFilter", - "#Microsoft.Azure.Search.CjkBigramTokenFilter": "CjkBigramTokenFilter", - "#Microsoft.Azure.Search.CommonGramTokenFilter": "CommonGramTokenFilter", - "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter": "DictionaryDecompounderTokenFilter", - "#Microsoft.Azure.Search.EdgeNGramTokenFilter": "EdgeNGramTokenFilter", - "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2": "EdgeNGramTokenFilterV2", - "#Microsoft.Azure.Search.ElisionTokenFilter": "ElisionTokenFilter", - "#Microsoft.Azure.Search.KeepTokenFilter": "KeepTokenFilter", - "#Microsoft.Azure.Search.KeywordMarkerTokenFilter": "KeywordMarkerTokenFilter", - "#Microsoft.Azure.Search.LengthTokenFilter": "LengthTokenFilter", - "#Microsoft.Azure.Search.LimitTokenFilter": "LimitTokenFilter", - "#Microsoft.Azure.Search.NGramTokenFilter": "NGramTokenFilter", - "#Microsoft.Azure.Search.NGramTokenFilterV2": "NGramTokenFilterV2", - "#Microsoft.Azure.Search.PatternCaptureTokenFilter": "PatternCaptureTokenFilter", - "#Microsoft.Azure.Search.PatternReplaceTokenFilter": "PatternReplaceTokenFilter", - "#Microsoft.Azure.Search.PhoneticTokenFilter": "PhoneticTokenFilter", - "#Microsoft.Azure.Search.ShingleTokenFilter": "ShingleTokenFilter", - "#Microsoft.Azure.Search.SnowballTokenFilter": "SnowballTokenFilter", - "#Microsoft.Azure.Search.StemmerOverrideTokenFilter": "StemmerOverrideTokenFilter", - "#Microsoft.Azure.Search.StemmerTokenFilter": "StemmerTokenFilter", - "#Microsoft.Azure.Search.StopwordsTokenFilter": "StopwordsTokenFilter", - "#Microsoft.Azure.Search.SynonymTokenFilter": "SynonymTokenFilter", - "#Microsoft.Azure.Search.TruncateTokenFilter": "TruncateTokenFilter", - "#Microsoft.Azure.Search.UniqueTokenFilter": "UniqueTokenFilter", - "#Microsoft.Azure.Search.WordDelimiterTokenFilter": "WordDelimiterTokenFilter", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class AsciiFoldingTokenFilter(TokenFilter): - """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 - ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such - equivalents exist. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar preserve_original: A value indicating whether the original token will be kept. Default is - false. - :vartype preserve_original: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "preserve_original": {"key": "preserveOriginal", "type": "bool"}, - } - - def __init__(self, *, name: str, preserve_original: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword preserve_original: A value indicating whether the original token will be kept. Default - is false. - :paramtype preserve_original: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.AsciiFoldingTokenFilter" - self.preserve_original = preserve_original - - -class AzureActiveDirectoryApplicationCredentials(_serialization.Model): # pylint: disable=name-too-long - """Credentials of a registered application created for your search service, used for authenticated - access to the encryption keys stored in Azure Key Vault. - - All required parameters must be populated in order to send to server. - - :ivar application_id: An AAD Application ID that was granted the required access permissions to - the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID - should not be confused with the Object ID for your AAD Application. Required. - :vartype application_id: str - :ivar application_secret: The authentication key of the specified AAD application. - :vartype application_secret: str - """ - - _validation = { - "application_id": {"required": True}, - } - - _attribute_map = { - "application_id": {"key": "applicationId", "type": "str"}, - "application_secret": {"key": "applicationSecret", "type": "str"}, - } - - def __init__(self, *, application_id: str, application_secret: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword application_id: An AAD Application ID that was granted the required access permissions - to the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID - should not be confused with the Object ID for your AAD Application. Required. - :paramtype application_id: str - :keyword application_secret: The authentication key of the specified AAD application. - :paramtype application_secret: str - """ - super().__init__(**kwargs) - self.application_id = application_id - self.application_secret = application_secret - - -class KnowledgeSource(_serialization.Model): - """Represents a knowledge source definition. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureBlobKnowledgeSource, SearchIndexKnowledgeSource - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex" and - "azureBlob". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the agent. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - } - - _subtype_map = {"kind": {"azureBlob": "AzureBlobKnowledgeSource", "searchIndex": "SearchIndexKnowledgeSource"}} - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the agent. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.kind: Optional[str] = None - self.e_tag = e_tag - self.encryption_key = encryption_key - - -class AzureBlobKnowledgeSource(KnowledgeSource): - """Configuration for Azure Blob Storage knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex" and - "azureBlob". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the agent. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar azure_blob_parameters: The type of the knowledge source. Required. - :vartype azure_blob_parameters: - ~azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - "azure_blob_parameters": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "azure_blob_parameters": {"key": "azureBlobParameters", "type": "AzureBlobKnowledgeSourceParameters"}, - } - - def __init__( - self, - *, - name: str, - azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters", - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the agent. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword azure_blob_parameters: The type of the knowledge source. Required. - :paramtype azure_blob_parameters: - ~azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "azureBlob" - self.azure_blob_parameters = azure_blob_parameters - - -class AzureBlobKnowledgeSourceParameters(_serialization.Model): - """Parameters for Azure Blob Storage knowledge source. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar identity: An explicit identity to use for this knowledge source. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar connection_string: Key-based connection string or the ResourceId format if using a - managed identity. Required. - :vartype connection_string: str - :ivar container_name: The name of the blob storage container. Required. - :vartype container_name: str - :ivar folder_path: Optional folder path within the container. - :vartype folder_path: str - :ivar embedding_model: Optional vectorizer configuration for vectorizing content. - :vartype embedding_model: ~azure.search.documents.indexes.models.VectorSearchVectorizer - :ivar chat_completion_model: Optional chat completion model for image verbalization or context - extraction. - :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeAgentModel - :ivar ingestion_schedule: Optional schedule for data ingestion. - :vartype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :ivar created_resources: Resources created by the knowledge source. - :vartype created_resources: dict[str, str] - :ivar disable_image_verbalization: Indicates whether image verbalization should be disabled. - :vartype disable_image_verbalization: bool - """ - - _validation = { - "connection_string": {"required": True}, - "container_name": {"required": True}, - "created_resources": {"readonly": True}, - } - - _attribute_map = { - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "connection_string": {"key": "connectionString", "type": "str"}, - "container_name": {"key": "containerName", "type": "str"}, - "folder_path": {"key": "folderPath", "type": "str"}, - "embedding_model": {"key": "embeddingModel", "type": "VectorSearchVectorizer"}, - "chat_completion_model": {"key": "chatCompletionModel", "type": "KnowledgeAgentModel"}, - "ingestion_schedule": {"key": "ingestionSchedule", "type": "IndexingSchedule"}, - "created_resources": {"key": "createdResources", "type": "{str}"}, - "disable_image_verbalization": {"key": "disableImageVerbalization", "type": "bool"}, - } - - def __init__( - self, - *, - connection_string: str, - container_name: str, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - folder_path: Optional[str] = None, - embedding_model: Optional["_models.VectorSearchVectorizer"] = None, - chat_completion_model: Optional["_models.KnowledgeAgentModel"] = None, - ingestion_schedule: Optional["_models.IndexingSchedule"] = None, - disable_image_verbalization: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword identity: An explicit identity to use for this knowledge source. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword connection_string: Key-based connection string or the ResourceId format if using a - managed identity. Required. - :paramtype connection_string: str - :keyword container_name: The name of the blob storage container. Required. - :paramtype container_name: str - :keyword folder_path: Optional folder path within the container. - :paramtype folder_path: str - :keyword embedding_model: Optional vectorizer configuration for vectorizing content. - :paramtype embedding_model: ~azure.search.documents.indexes.models.VectorSearchVectorizer - :keyword chat_completion_model: Optional chat completion model for image verbalization or - context extraction. - :paramtype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeAgentModel - :keyword ingestion_schedule: Optional schedule for data ingestion. - :paramtype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :keyword disable_image_verbalization: Indicates whether image verbalization should be disabled. - :paramtype disable_image_verbalization: bool - """ - super().__init__(**kwargs) - self.identity = identity - self.connection_string = connection_string - self.container_name = container_name - self.folder_path = folder_path - self.embedding_model = embedding_model - self.chat_completion_model = chat_completion_model - self.ingestion_schedule = ingestion_schedule - self.created_resources: Optional[dict[str, str]] = None - self.disable_image_verbalization = disable_image_verbalization - - -class AzureMachineLearningParameters(_serialization.Model): - """Specifies the properties for connecting to an AML vectorizer. - - All required parameters must be populated in order to send to server. - - :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - Required. - :vartype scoring_uri: str - :ivar authentication_key: (Required for key authentication) The key for the AML service. - :vartype authentication_key: str - :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID - of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :vartype resource_id: str - :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the - API call. - :vartype timeout: ~datetime.timedelta - :ivar region: (Optional for token authentication). The region the AML service is deployed in. - :vartype region: str - :ivar model_name: The name of the embedding model from the Azure AI Foundry Catalog that is - deployed at the provided endpoint. Known values are: - "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", - "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", - "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", - "Cohere-embed-v3-english", "Cohere-embed-v3-multilingual", and "Cohere-embed-v4". - :vartype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName - """ - - _validation = { - "scoring_uri": {"required": True}, - } - - _attribute_map = { - "scoring_uri": {"key": "uri", "type": "str"}, - "authentication_key": {"key": "key", "type": "str"}, - "resource_id": {"key": "resourceId", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "region": {"key": "region", "type": "str"}, - "model_name": {"key": "modelName", "type": "str"}, - } - - def __init__( - self, - *, - scoring_uri: str, - authentication_key: Optional[str] = None, - resource_id: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - region: Optional[str] = None, - model_name: Optional[Union[str, "_models.AIFoundryModelCatalogName"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - Required. - :paramtype scoring_uri: str - :keyword authentication_key: (Required for key authentication) The key for the AML service. - :paramtype authentication_key: str - :keyword resource_id: (Required for token authentication). The Azure Resource Manager resource - ID of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :paramtype resource_id: str - :keyword timeout: (Optional) When specified, indicates the timeout for the http client making - the API call. - :paramtype timeout: ~datetime.timedelta - :keyword region: (Optional for token authentication). The region the AML service is deployed - in. - :paramtype region: str - :keyword model_name: The name of the embedding model from the Azure AI Foundry Catalog that is - deployed at the provided endpoint. Known values are: - "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", - "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", - "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", - "Cohere-embed-v3-english", "Cohere-embed-v3-multilingual", and "Cohere-embed-v4". - :paramtype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName - """ - super().__init__(**kwargs) - self.scoring_uri = scoring_uri - self.authentication_key = authentication_key - self.resource_id = resource_id - self.timeout = timeout - self.region = region - self.model_name = model_name - - -class SearchIndexerSkill(_serialization.Model): - """Base type for skills. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureMachineLearningSkill, WebApiSkill, AzureOpenAIEmbeddingSkill, CustomEntityLookupSkill, - EntityRecognitionSkill, KeyPhraseExtractionSkill, LanguageDetectionSkill, MergeSkill, - PIIDetectionSkill, SentimentSkill, SplitSkill, TextTranslationSkill, EntityLinkingSkill, - EntityRecognitionSkillV3, SentimentSkillV3, ConditionalSkill, DocumentExtractionSkill, - DocumentIntelligenceLayoutSkill, ShaperSkill, ImageAnalysisSkill, OcrSkill, - VisionVectorizeSkill - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Skills.Custom.AmlSkill": "AzureMachineLearningSkill", - "#Microsoft.Skills.Custom.WebApiSkill": "WebApiSkill", - "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill": "AzureOpenAIEmbeddingSkill", - "#Microsoft.Skills.Text.CustomEntityLookupSkill": "CustomEntityLookupSkill", - "#Microsoft.Skills.Text.EntityRecognitionSkill": "EntityRecognitionSkill", - "#Microsoft.Skills.Text.KeyPhraseExtractionSkill": "KeyPhraseExtractionSkill", - "#Microsoft.Skills.Text.LanguageDetectionSkill": "LanguageDetectionSkill", - "#Microsoft.Skills.Text.MergeSkill": "MergeSkill", - "#Microsoft.Skills.Text.PIIDetectionSkill": "PIIDetectionSkill", - "#Microsoft.Skills.Text.SentimentSkill": "SentimentSkill", - "#Microsoft.Skills.Text.SplitSkill": "SplitSkill", - "#Microsoft.Skills.Text.TranslationSkill": "TextTranslationSkill", - "#Microsoft.Skills.Text.V3.EntityLinkingSkill": "EntityLinkingSkill", - "#Microsoft.Skills.Text.V3.EntityRecognitionSkill": "EntityRecognitionSkillV3", - "#Microsoft.Skills.Text.V3.SentimentSkill": "SentimentSkillV3", - "#Microsoft.Skills.Util.ConditionalSkill": "ConditionalSkill", - "#Microsoft.Skills.Util.DocumentExtractionSkill": "DocumentExtractionSkill", - "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill": "DocumentIntelligenceLayoutSkill", - "#Microsoft.Skills.Util.ShaperSkill": "ShaperSkill", - "#Microsoft.Skills.Vision.ImageAnalysisSkill": "ImageAnalysisSkill", - "#Microsoft.Skills.Vision.OcrSkill": "OcrSkill", - "#Microsoft.Skills.Vision.VectorizeSkill": "VisionVectorizeSkill", - } - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - self.description = description - self.context = context - self.inputs = inputs - self.outputs = outputs - - -class AzureMachineLearningSkill(SearchIndexerSkill): - """The AML skill allows you to extend AI enrichment with a custom Azure Machine Learning (AML) - model. Once an AML model is trained and deployed, an AML skill integrates it into AI - enrichment. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - :vartype scoring_uri: str - :ivar authentication_key: (Required for key authentication) The key for the AML service. - :vartype authentication_key: str - :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID - of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :vartype resource_id: str - :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the - API call. - :vartype timeout: ~datetime.timedelta - :ivar region: (Optional for token authentication). The region the AML service is deployed in. - :vartype region: str - :ivar degree_of_parallelism: (Optional) When specified, indicates the number of calls the - indexer will make in parallel to the endpoint you have provided. You can decrease this value if - your endpoint is failing under too high of a request load, or raise it if your endpoint is able - to accept more requests and you would like an increase in the performance of the indexer. If - not set, a default value of 5 is used. The degreeOfParallelism can be set to a maximum of 10 - and a minimum of 1. - :vartype degree_of_parallelism: int - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "scoring_uri": {"key": "uri", "type": "str"}, - "authentication_key": {"key": "key", "type": "str"}, - "resource_id": {"key": "resourceId", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "region": {"key": "region", "type": "str"}, - "degree_of_parallelism": {"key": "degreeOfParallelism", "type": "int"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - scoring_uri: Optional[str] = None, - authentication_key: Optional[str] = None, - resource_id: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - region: Optional[str] = None, - degree_of_parallelism: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword scoring_uri: (Required for no authentication or key authentication) The scoring URI of - the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. - :paramtype scoring_uri: str - :keyword authentication_key: (Required for key authentication) The key for the AML service. - :paramtype authentication_key: str - :keyword resource_id: (Required for token authentication). The Azure Resource Manager resource - ID of the AML service. It should be in the format - subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. - :paramtype resource_id: str - :keyword timeout: (Optional) When specified, indicates the timeout for the http client making - the API call. - :paramtype timeout: ~datetime.timedelta - :keyword region: (Optional for token authentication). The region the AML service is deployed - in. - :paramtype region: str - :keyword degree_of_parallelism: (Optional) When specified, indicates the number of calls the - indexer will make in parallel to the endpoint you have provided. You can decrease this value if - your endpoint is failing under too high of a request load, or raise it if your endpoint is able - to accept more requests and you would like an increase in the performance of the indexer. If - not set, a default value of 5 is used. The degreeOfParallelism can be set to a maximum of 10 - and a minimum of 1. - :paramtype degree_of_parallelism: int - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Custom.AmlSkill" - self.scoring_uri = scoring_uri - self.authentication_key = authentication_key - self.resource_id = resource_id - self.timeout = timeout - self.region = region - self.degree_of_parallelism = degree_of_parallelism - - -class AzureMachineLearningVectorizer(VectorSearchVectorizer): - """Specifies an Azure Machine Learning endpoint deployed via the Azure AI Foundry Model Catalog - for generating the vector embedding of a query string. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar aml_parameters: Specifies the properties of the AML vectorizer. - :vartype aml_parameters: ~azure.search.documents.indexes.models.AzureMachineLearningParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "aml_parameters": {"key": "amlParameters", "type": "AzureMachineLearningParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - aml_parameters: Optional["_models.AzureMachineLearningParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword aml_parameters: Specifies the properties of the AML vectorizer. - :paramtype aml_parameters: - ~azure.search.documents.indexes.models.AzureMachineLearningParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "aml" - self.aml_parameters = aml_parameters - - -class AzureOpenAIVectorizerParameters(_serialization.Model): - """Specifies the parameters for connecting to the Azure OpenAI resource. - - :ivar resource_url: The resource URI of the Azure OpenAI resource. - :vartype resource_url: str - :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :vartype deployment_name: str - :ivar api_key: API key of the designated Azure OpenAI resource. - :vartype api_key: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", and - "gpt-4.1-nano". - :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - """ - - _attribute_map = { - "resource_url": {"key": "resourceUri", "type": "str"}, - "deployment_name": {"key": "deploymentId", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - "model_name": {"key": "modelName", "type": "str"}, - } - - def __init__( - self, - *, - resource_url: Optional[str] = None, - deployment_name: Optional[str] = None, - api_key: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_url: The resource URI of the Azure OpenAI resource. - :paramtype resource_url: str - :keyword deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :paramtype deployment_name: str - :keyword api_key: API key of the designated Azure OpenAI resource. - :paramtype api_key: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword model_name: The name of the embedding model that is deployed at the provided - deploymentId path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", and - "gpt-4.1-nano". - :paramtype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - """ - super().__init__(**kwargs) - self.resource_url = resource_url - self.deployment_name = deployment_name - self.api_key = api_key - self.auth_identity = auth_identity - self.model_name = model_name - - -class AzureOpenAIEmbeddingSkill(SearchIndexerSkill, AzureOpenAIVectorizerParameters): - """Allows you to generate a vector embedding for a given text input using the Azure OpenAI - resource. - - All required parameters must be populated in order to send to server. - - :ivar resource_url: The resource URI of the Azure OpenAI resource. - :vartype resource_url: str - :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :vartype deployment_name: str - :ivar api_key: API key of the designated Azure OpenAI resource. - :vartype api_key: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", and - "gpt-4.1-nano". - :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar dimensions: The number of dimensions the resulting output embeddings should have. Only - supported in text-embedding-3 and later models. - :vartype dimensions: int - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "resource_url": {"key": "resourceUri", "type": "str"}, - "deployment_name": {"key": "deploymentId", "type": "str"}, - "api_key": {"key": "apiKey", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - "model_name": {"key": "modelName", "type": "str"}, - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "dimensions": {"key": "dimensions", "type": "int"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - resource_url: Optional[str] = None, - deployment_name: Optional[str] = None, - api_key: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - dimensions: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_url: The resource URI of the Azure OpenAI resource. - :paramtype resource_url: str - :keyword deployment_name: ID of the Azure OpenAI model deployment on the designated resource. - :paramtype deployment_name: str - :keyword api_key: API key of the designated Azure OpenAI resource. - :paramtype api_key: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword model_name: The name of the embedding model that is deployed at the provided - deploymentId path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", - "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", and - "gpt-4.1-nano". - :paramtype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword dimensions: The number of dimensions the resulting output embeddings should have. Only - supported in text-embedding-3 and later models. - :paramtype dimensions: int - """ - super().__init__( - name=name, - description=description, - context=context, - inputs=inputs, - outputs=outputs, - resource_url=resource_url, - deployment_name=deployment_name, - api_key=api_key, - auth_identity=auth_identity, - model_name=model_name, - **kwargs - ) - self.resource_url = resource_url - self.deployment_name = deployment_name - self.api_key = api_key - self.auth_identity = auth_identity - self.model_name = model_name - self.odata_type: str = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill" - self.dimensions = dimensions - self.name = name - self.description = description - self.context = context - self.inputs = inputs - self.outputs = outputs - - -class AzureOpenAITokenizerParameters(_serialization.Model): - """AzureOpenAITokenizerParameters. - - :ivar encoder_model_name: Only applies if the unit is set to azureOpenAITokens. Options include - 'R50k_base', 'P50k_base', 'P50k_edit' and 'CL100k_base'. The default value is 'CL100k_base'. - Known values are: "r50k_base", "p50k_base", "p50k_edit", and "cl100k_base". - :vartype encoder_model_name: str or - ~azure.search.documents.indexes.models.SplitSkillEncoderModelName - :ivar allowed_special_tokens: (Optional) Only applies if the unit is set to azureOpenAITokens. - This parameter defines a collection of special tokens that are permitted within the - tokenization process. - :vartype allowed_special_tokens: list[str] - """ - - _attribute_map = { - "encoder_model_name": {"key": "encoderModelName", "type": "str"}, - "allowed_special_tokens": {"key": "allowedSpecialTokens", "type": "[str]"}, - } - - def __init__( - self, - *, - encoder_model_name: Optional[Union[str, "_models.SplitSkillEncoderModelName"]] = None, - allowed_special_tokens: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword encoder_model_name: Only applies if the unit is set to azureOpenAITokens. Options - include 'R50k_base', 'P50k_base', 'P50k_edit' and 'CL100k_base'. The default value is - 'CL100k_base'. Known values are: "r50k_base", "p50k_base", "p50k_edit", and "cl100k_base". - :paramtype encoder_model_name: str or - ~azure.search.documents.indexes.models.SplitSkillEncoderModelName - :keyword allowed_special_tokens: (Optional) Only applies if the unit is set to - azureOpenAITokens. This parameter defines a collection of special tokens that are permitted - within the tokenization process. - :paramtype allowed_special_tokens: list[str] - """ - super().__init__(**kwargs) - self.encoder_model_name = encoder_model_name - self.allowed_special_tokens = allowed_special_tokens - - -class AzureOpenAIVectorizer(VectorSearchVectorizer): - """Specifies the Azure OpenAI resource used to vectorize a query string. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar parameters: Contains the parameters specific to Azure OpenAI embedding vectorization. - :vartype parameters: ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "parameters": {"key": "azureOpenAIParameters", "type": "AzureOpenAIVectorizerParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword parameters: Contains the parameters specific to Azure OpenAI embedding vectorization. - :paramtype parameters: ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "azureOpenAI" - self.parameters = parameters - - -class VectorSearchCompression(_serialization.Model): - """Contains configuration options specific to the compression method used during indexing or - querying. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - BinaryQuantizationCompression, ScalarQuantizationCompression - - All required parameters must be populated in order to send to server. - - :ivar compression_name: The name to associate with this particular configuration. Required. - :vartype compression_name: str - :ivar kind: The name of the kind of compression method being configured for use with vector - search. Required. Known values are: "scalarQuantization" and "binaryQuantization". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind - :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated - using compressed vectors are obtained, they will be reranked again by recalculating the - full-precision similarity scores. This will improve recall at the expense of latency. - :vartype rerank_with_original_vectors: bool - :ivar default_oversampling: Default oversampling factor. Oversampling will internally request - more documents (specified by this multiplier) in the initial search. This increases the set of - results that will be reranked using recomputed similarity scores from full-precision vectors. - Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :vartype default_oversampling: float - :ivar rescoring_options: Contains the options for rescoring. - :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the - vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :vartype truncation_dimension: int - """ - - _validation = { - "compression_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "compression_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "rerank_with_original_vectors": {"key": "rerankWithOriginalVectors", "type": "bool"}, - "default_oversampling": {"key": "defaultOversampling", "type": "float"}, - "rescoring_options": {"key": "rescoringOptions", "type": "RescoringOptions"}, - "truncation_dimension": {"key": "truncationDimension", "type": "int"}, - } - - _subtype_map = { - "kind": { - "binaryQuantization": "BinaryQuantizationCompression", - "scalarQuantization": "ScalarQuantizationCompression", - } - } - - def __init__( - self, - *, - compression_name: str, - rerank_with_original_vectors: Optional[bool] = None, - default_oversampling: Optional[float] = None, - rescoring_options: Optional["_models.RescoringOptions"] = None, - truncation_dimension: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword compression_name: The name to associate with this particular configuration. Required. - :paramtype compression_name: str - :keyword rerank_with_original_vectors: If set to true, once the ordered set of results - calculated using compressed vectors are obtained, they will be reranked again by recalculating - the full-precision similarity scores. This will improve recall at the expense of latency. - :paramtype rerank_with_original_vectors: bool - :keyword default_oversampling: Default oversampling factor. Oversampling will internally - request more documents (specified by this multiplier) in the initial search. This increases the - set of results that will be reranked using recomputed similarity scores from full-precision - vectors. Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :paramtype default_oversampling: float - :keyword rescoring_options: Contains the options for rescoring. - :paramtype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :keyword truncation_dimension: The number of dimensions to truncate the vectors to. Truncating - the vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :paramtype truncation_dimension: int - """ - super().__init__(**kwargs) - self.compression_name = compression_name - self.kind: Optional[str] = None - self.rerank_with_original_vectors = rerank_with_original_vectors - self.default_oversampling = default_oversampling - self.rescoring_options = rescoring_options - self.truncation_dimension = truncation_dimension - - -class BinaryQuantizationCompression(VectorSearchCompression): - """Contains configuration options specific to the binary quantization compression method used - during indexing and querying. - - All required parameters must be populated in order to send to server. - - :ivar compression_name: The name to associate with this particular configuration. Required. - :vartype compression_name: str - :ivar kind: The name of the kind of compression method being configured for use with vector - search. Required. Known values are: "scalarQuantization" and "binaryQuantization". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind - :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated - using compressed vectors are obtained, they will be reranked again by recalculating the - full-precision similarity scores. This will improve recall at the expense of latency. - :vartype rerank_with_original_vectors: bool - :ivar default_oversampling: Default oversampling factor. Oversampling will internally request - more documents (specified by this multiplier) in the initial search. This increases the set of - results that will be reranked using recomputed similarity scores from full-precision vectors. - Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :vartype default_oversampling: float - :ivar rescoring_options: Contains the options for rescoring. - :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the - vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :vartype truncation_dimension: int - """ - - _validation = { - "compression_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "compression_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "rerank_with_original_vectors": {"key": "rerankWithOriginalVectors", "type": "bool"}, - "default_oversampling": {"key": "defaultOversampling", "type": "float"}, - "rescoring_options": {"key": "rescoringOptions", "type": "RescoringOptions"}, - "truncation_dimension": {"key": "truncationDimension", "type": "int"}, - } - - def __init__( - self, - *, - compression_name: str, - rerank_with_original_vectors: Optional[bool] = None, - default_oversampling: Optional[float] = None, - rescoring_options: Optional["_models.RescoringOptions"] = None, - truncation_dimension: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword compression_name: The name to associate with this particular configuration. Required. - :paramtype compression_name: str - :keyword rerank_with_original_vectors: If set to true, once the ordered set of results - calculated using compressed vectors are obtained, they will be reranked again by recalculating - the full-precision similarity scores. This will improve recall at the expense of latency. - :paramtype rerank_with_original_vectors: bool - :keyword default_oversampling: Default oversampling factor. Oversampling will internally - request more documents (specified by this multiplier) in the initial search. This increases the - set of results that will be reranked using recomputed similarity scores from full-precision - vectors. Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :paramtype default_oversampling: float - :keyword rescoring_options: Contains the options for rescoring. - :paramtype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :keyword truncation_dimension: The number of dimensions to truncate the vectors to. Truncating - the vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :paramtype truncation_dimension: int - """ - super().__init__( - compression_name=compression_name, - rerank_with_original_vectors=rerank_with_original_vectors, - default_oversampling=default_oversampling, - rescoring_options=rescoring_options, - truncation_dimension=truncation_dimension, - **kwargs - ) - self.kind: str = "binaryQuantization" - - -class SimilarityAlgorithm(_serialization.Model): - """Base type for similarity algorithms. Similarity algorithms are used to calculate scores that - tie queries to documents. The higher the score, the more relevant the document is to that - specific query. Those scores are used to rank the search results. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - BM25SimilarityAlgorithm, ClassicSimilarityAlgorithm - - All required parameters must be populated in order to send to server. - - :ivar odata_type: Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.BM25Similarity": "BM25SimilarityAlgorithm", - "#Microsoft.Azure.Search.ClassicSimilarity": "ClassicSimilarityAlgorithm", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class BM25SimilarityAlgorithm(SimilarityAlgorithm): - """Ranking function based on the Okapi BM25 similarity algorithm. BM25 is a TF-IDF-like algorithm - that includes length normalization (controlled by the 'b' parameter) as well as term frequency - saturation (controlled by the 'k1' parameter). - - All required parameters must be populated in order to send to server. - - :ivar odata_type: Required. - :vartype odata_type: str - :ivar k1: This property controls the scaling function between the term frequency of each - matching terms and the final relevance score of a document-query pair. By default, a value of - 1.2 is used. A value of 0.0 means the score does not scale with an increase in term frequency. - :vartype k1: float - :ivar b: This property controls how the length of a document affects the relevance score. By - default, a value of 0.75 is used. A value of 0.0 means no length normalization is applied, - while a value of 1.0 means the score is fully normalized by the length of the document. - :vartype b: float - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "k1": {"key": "k1", "type": "float"}, - "b": {"key": "b", "type": "float"}, - } - - def __init__(self, *, k1: Optional[float] = None, b: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword k1: This property controls the scaling function between the term frequency of each - matching terms and the final relevance score of a document-query pair. By default, a value of - 1.2 is used. A value of 0.0 means the score does not scale with an increase in term frequency. - :paramtype k1: float - :keyword b: This property controls how the length of a document affects the relevance score. By - default, a value of 0.75 is used. A value of 0.0 means no length normalization is applied, - while a value of 1.0 means the score is fully normalized by the length of the document. - :paramtype b: float - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.BM25Similarity" - self.k1 = k1 - self.b = b - - -class CharFilter(_serialization.Model): - """Base type for character filters. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MappingCharFilter, PatternReplaceCharFilter - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of char filter. Required. - :vartype odata_type: str - :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.MappingCharFilter": "MappingCharFilter", - "#Microsoft.Azure.Search.PatternReplaceCharFilter": "PatternReplaceCharFilter", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the char filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class ChatCompletionResponseFormat(_serialization.Model): - """Determines how the language model's response should be serialized. Defaults to 'text'. - - :ivar type: Specifies how the LLM should format the response. Possible values: 'text' (plain - string), 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). Known - values are: "text", "jsonObject", and "jsonSchema". - :vartype type: str or ~azure.search.documents.indexes.models.ChatCompletionResponseFormatType - :ivar chat_completion_schema_properties: An open dictionary for extended properties. Required - if 'type' == 'json_schema'. - :vartype chat_completion_schema_properties: - ~azure.search.documents.indexes.models.ChatCompletionResponseFormatJsonSchemaProperties - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "chat_completion_schema_properties": { - "key": "jsonSchemaProperties", - "type": "ChatCompletionResponseFormatJsonSchemaProperties", - }, - } - - def __init__( - self, - *, - type: Union[str, "_models.ChatCompletionResponseFormatType"] = "text", - chat_completion_schema_properties: Optional["_models.ChatCompletionResponseFormatJsonSchemaProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: Specifies how the LLM should format the response. Possible values: 'text' (plain - string), 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). Known - values are: "text", "jsonObject", and "jsonSchema". - :paramtype type: str or ~azure.search.documents.indexes.models.ChatCompletionResponseFormatType - :keyword chat_completion_schema_properties: An open dictionary for extended properties. - Required if 'type' == 'json_schema'. - :paramtype chat_completion_schema_properties: - ~azure.search.documents.indexes.models.ChatCompletionResponseFormatJsonSchemaProperties - """ - super().__init__(**kwargs) - self.type = type - self.chat_completion_schema_properties = chat_completion_schema_properties - - -class ChatCompletionResponseFormatJsonSchemaProperties(_serialization.Model): # pylint: disable=name-too-long - """An open dictionary for extended properties. Required if 'type' == 'json_schema'. - - :ivar name: Name of the json schema the model will adhere to. - :vartype name: str - :ivar description: Description of the json schema the model will adhere to. - :vartype description: str - :ivar strict: Whether or not the model's response should use structured outputs. Default is - true. - :vartype strict: bool - :ivar schema: Object defining the custom schema the model will use to structure its output. - :vartype schema: ~azure.search.documents.indexes.models.ChatCompletionSchema - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "strict": {"key": "strict", "type": "bool"}, - "schema": {"key": "schema", "type": "ChatCompletionSchema"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - strict: bool = True, - schema: Optional["_models.ChatCompletionSchema"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Name of the json schema the model will adhere to. - :paramtype name: str - :keyword description: Description of the json schema the model will adhere to. - :paramtype description: str - :keyword strict: Whether or not the model's response should use structured outputs. Default is - true. - :paramtype strict: bool - :keyword schema: Object defining the custom schema the model will use to structure its output. - :paramtype schema: ~azure.search.documents.indexes.models.ChatCompletionSchema - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.strict = strict - self.schema = schema - - -class ChatCompletionSchema(_serialization.Model): - """Object defining the custom schema the model will use to structure its output. - - :ivar type: Type of schema representation. Usually 'object'. Default is 'object'. - :vartype type: str - :ivar properties: A JSON-formatted string that defines the output schema's properties and - constraints for the model. - :vartype properties: str - :ivar required: An array of the property names that are required to be part of the model's - response. All properties must be included for structured outputs. - :vartype required: list[str] - :ivar additional_properties: Controls whether it is allowable for an object to contain - additional keys / values that were not defined in the JSON Schema. Default is false. - :vartype additional_properties: bool - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "str"}, - "required": {"key": "required", "type": "[str]"}, - "additional_properties": {"key": "additionalProperties", "type": "bool"}, - } - - def __init__( - self, - *, - type: str = "object", - properties: Optional[str] = None, - required: Optional[list[str]] = None, - additional_properties: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword type: Type of schema representation. Usually 'object'. Default is 'object'. - :paramtype type: str - :keyword properties: A JSON-formatted string that defines the output schema's properties and - constraints for the model. - :paramtype properties: str - :keyword required: An array of the property names that are required to be part of the model's - response. All properties must be included for structured outputs. - :paramtype required: list[str] - :keyword additional_properties: Controls whether it is allowable for an object to contain - additional keys / values that were not defined in the JSON Schema. Default is false. - :paramtype additional_properties: bool - """ - super().__init__(**kwargs) - self.type = type - self.properties = properties - self.required = required - self.additional_properties = additional_properties # type: ignore[assignment] - - -class WebApiSkill(SearchIndexerSkill): - """A skill that can call a Web API endpoint, allowing you to extend a skillset by having it call - your custom code. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ChatCompletionSkill - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar uri: The url for the Web API. Required. - :vartype uri: str - :ivar http_headers: The headers required to make the http request. - :vartype http_headers: dict[str, str] - :ivar http_method: The method for the http request. - :vartype http_method: str - :ivar timeout: The desired timeout for the request. Default is 30 seconds. - :vartype timeout: ~datetime.timedelta - :ivar batch_size: The desired batch size which indicates number of documents. - :vartype batch_size: int - :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web - API. - :vartype degree_of_parallelism: int - :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "uri": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "uri": {"key": "uri", "type": "str"}, - "http_headers": {"key": "httpHeaders", "type": "{str}"}, - "http_method": {"key": "httpMethod", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "batch_size": {"key": "batchSize", "type": "int"}, - "degree_of_parallelism": {"key": "degreeOfParallelism", "type": "int"}, - "auth_resource_id": {"key": "authResourceId", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - } - - _subtype_map = {"odata_type": {"#Microsoft.Skills.Custom.ChatCompletionSkill": "ChatCompletionSkill"}} - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - uri: str, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, - http_method: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - batch_size: Optional[int] = None, - degree_of_parallelism: Optional[int] = None, - auth_resource_id: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword uri: The url for the Web API. Required. - :paramtype uri: str - :keyword http_headers: The headers required to make the http request. - :paramtype http_headers: dict[str, str] - :keyword http_method: The method for the http request. - :paramtype http_method: str - :keyword timeout: The desired timeout for the request. Default is 30 seconds. - :paramtype timeout: ~datetime.timedelta - :keyword batch_size: The desired batch size which indicates number of documents. - :paramtype batch_size: int - :keyword degree_of_parallelism: If set, the number of parallel calls that can be made to the - Web API. - :paramtype degree_of_parallelism: int - :keyword auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :paramtype auth_resource_id: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Custom.WebApiSkill" - self.uri = uri - self.http_headers = http_headers - self.http_method = http_method - self.timeout = timeout - self.batch_size = batch_size - self.degree_of_parallelism = degree_of_parallelism - self.auth_resource_id = auth_resource_id - self.auth_identity = auth_identity - - -class ChatCompletionSkill(WebApiSkill): - """A skill that calls a language model via Azure AI Foundry's Chat Completions endpoint. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar uri: The url for the Web API. Required. - :vartype uri: str - :ivar http_headers: The headers required to make the http request. - :vartype http_headers: dict[str, str] - :ivar http_method: The method for the http request. - :vartype http_method: str - :ivar timeout: The desired timeout for the request. Default is 30 seconds. - :vartype timeout: ~datetime.timedelta - :ivar batch_size: The desired batch size which indicates number of documents. - :vartype batch_size: int - :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web - API. - :vartype degree_of_parallelism: int - :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot be - specified at the same time. - :vartype api_key: str - :ivar common_model_parameters: Common language model parameters that customers can tweak. If - omitted, reasonable defaults will be applied. - :vartype common_model_parameters: ~azure.search.documents.indexes.models.CommonModelParameters - :ivar extra_parameters: Open-type dictionary for model-specific parameters that should be - appended to the chat completions call. Follows Azure AI Foundry’s extensibility pattern. - :vartype extra_parameters: dict[str, any] - :ivar extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. Default - is 'error'. Known values are: "passThrough", "drop", and "error". - :vartype extra_parameters_behavior: str or - ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior - :ivar response_format: Determines how the LLM should format its response. Defaults to 'text' - response type. - :vartype response_format: ~azure.search.documents.indexes.models.ChatCompletionResponseFormat - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "uri": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "uri": {"key": "uri", "type": "str"}, - "http_headers": {"key": "httpHeaders", "type": "{str}"}, - "http_method": {"key": "httpMethod", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "batch_size": {"key": "batchSize", "type": "int"}, - "degree_of_parallelism": {"key": "degreeOfParallelism", "type": "int"}, - "auth_resource_id": {"key": "authResourceId", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - "api_key": {"key": "apiKey", "type": "str"}, - "common_model_parameters": {"key": "commonModelParameters", "type": "CommonModelParameters"}, - "extra_parameters": {"key": "extraParameters", "type": "{object}"}, - "extra_parameters_behavior": {"key": "extraParametersBehavior", "type": "str"}, - "response_format": {"key": "responseFormat", "type": "ChatCompletionResponseFormat"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - uri: str, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, - http_method: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - batch_size: Optional[int] = None, - degree_of_parallelism: Optional[int] = None, - auth_resource_id: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - api_key: Optional[str] = None, - common_model_parameters: Optional["_models.CommonModelParameters"] = None, - extra_parameters: Optional[dict[str, Any]] = None, - extra_parameters_behavior: Union[str, "_models.ChatCompletionExtraParametersBehavior"] = "error", - response_format: Optional["_models.ChatCompletionResponseFormat"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword uri: The url for the Web API. Required. - :paramtype uri: str - :keyword http_headers: The headers required to make the http request. - :paramtype http_headers: dict[str, str] - :keyword http_method: The method for the http request. - :paramtype http_method: str - :keyword timeout: The desired timeout for the request. Default is 30 seconds. - :paramtype timeout: ~datetime.timedelta - :keyword batch_size: The desired batch size which indicates number of documents. - :paramtype batch_size: int - :keyword degree_of_parallelism: If set, the number of parallel calls that can be made to the - Web API. - :paramtype degree_of_parallelism: int - :keyword auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the custom skill connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :paramtype auth_resource_id: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot - be specified at the same time. - :paramtype api_key: str - :keyword common_model_parameters: Common language model parameters that customers can tweak. If - omitted, reasonable defaults will be applied. - :paramtype common_model_parameters: - ~azure.search.documents.indexes.models.CommonModelParameters - :keyword extra_parameters: Open-type dictionary for model-specific parameters that should be - appended to the chat completions call. Follows Azure AI Foundry’s extensibility pattern. - :paramtype extra_parameters: dict[str, any] - :keyword extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. - Default is 'error'. Known values are: "passThrough", "drop", and "error". - :paramtype extra_parameters_behavior: str or - ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior - :keyword response_format: Determines how the LLM should format its response. Defaults to 'text' - response type. - :paramtype response_format: ~azure.search.documents.indexes.models.ChatCompletionResponseFormat - """ - super().__init__( - name=name, - description=description, - context=context, - inputs=inputs, - outputs=outputs, - uri=uri, - http_headers=http_headers, - http_method=http_method, - timeout=timeout, - batch_size=batch_size, - degree_of_parallelism=degree_of_parallelism, - auth_resource_id=auth_resource_id, - auth_identity=auth_identity, - **kwargs - ) - self.odata_type: str = "#Microsoft.Skills.Custom.ChatCompletionSkill" - self.api_key = api_key - self.common_model_parameters = common_model_parameters - self.extra_parameters = extra_parameters - self.extra_parameters_behavior = extra_parameters_behavior - self.response_format = response_format - - -class CjkBigramTokenFilter(TokenFilter): - """Forms bigrams of CJK terms that are generated from the standard tokenizer. This token filter is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar ignore_scripts: The scripts to ignore. - :vartype ignore_scripts: list[str or - ~azure.search.documents.indexes.models.CjkBigramTokenFilterScripts] - :ivar output_unigrams: A value indicating whether to output both unigrams and bigrams (if - true), or just bigrams (if false). Default is false. - :vartype output_unigrams: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "ignore_scripts": {"key": "ignoreScripts", "type": "[str]"}, - "output_unigrams": {"key": "outputUnigrams", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - ignore_scripts: Optional[list[Union[str, "_models.CjkBigramTokenFilterScripts"]]] = None, - output_unigrams: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword ignore_scripts: The scripts to ignore. - :paramtype ignore_scripts: list[str or - ~azure.search.documents.indexes.models.CjkBigramTokenFilterScripts] - :keyword output_unigrams: A value indicating whether to output both unigrams and bigrams (if - true), or just bigrams (if false). Default is false. - :paramtype output_unigrams: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CjkBigramTokenFilter" - self.ignore_scripts = ignore_scripts - self.output_unigrams = output_unigrams - - -class ClassicSimilarityAlgorithm(SimilarityAlgorithm): - """Legacy similarity algorithm which uses the Lucene TFIDFSimilarity implementation of TF-IDF. - This variation of TF-IDF introduces static document length normalization as well as - coordinating factors that penalize documents that only partially match the searched queries. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ClassicSimilarity" - - -class LexicalTokenizer(_serialization.Model): - """Base type for tokenizers. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ClassicTokenizer, EdgeNGramTokenizer, KeywordTokenizer, KeywordTokenizerV2, - MicrosoftLanguageStemmingTokenizer, MicrosoftLanguageTokenizer, NGramTokenizer, - PathHierarchyTokenizerV2, PatternTokenizer, LuceneStandardTokenizer, LuceneStandardTokenizerV2, - UaxUrlEmailTokenizer - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.ClassicTokenizer": "ClassicTokenizer", - "#Microsoft.Azure.Search.EdgeNGramTokenizer": "EdgeNGramTokenizer", - "#Microsoft.Azure.Search.KeywordTokenizer": "KeywordTokenizer", - "#Microsoft.Azure.Search.KeywordTokenizerV2": "KeywordTokenizerV2", - "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer": "MicrosoftLanguageStemmingTokenizer", - "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer": "MicrosoftLanguageTokenizer", - "#Microsoft.Azure.Search.NGramTokenizer": "NGramTokenizer", - "#Microsoft.Azure.Search.PathHierarchyTokenizerV2": "PathHierarchyTokenizerV2", - "#Microsoft.Azure.Search.PatternTokenizer": "PatternTokenizer", - "#Microsoft.Azure.Search.StandardTokenizer": "LuceneStandardTokenizer", - "#Microsoft.Azure.Search.StandardTokenizerV2": "LuceneStandardTokenizerV2", - "#Microsoft.Azure.Search.UaxUrlEmailTokenizer": "UaxUrlEmailTokenizer", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class ClassicTokenizer(LexicalTokenizer): - """Grammar-based tokenizer that is suitable for processing most European-language documents. This - tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ClassicTokenizer" - self.max_token_length = max_token_length - - -class CognitiveServicesAccountKey(CognitiveServicesAccount): - """The multi-region account key of an Azure AI service resource that's attached to a skillset. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - :ivar key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :vartype key: str - """ - - _validation = { - "odata_type": {"required": True}, - "key": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "key": {"key": "key", "type": "str"}, - } - - def __init__(self, *, key: str, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - :keyword key: The key used to provision the Azure AI service resource attached to a skillset. - Required. - :paramtype key: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CognitiveServicesByKey" - self.key = key - - -class CommonGramTokenFilter(TokenFilter): - """Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed - too, with bigrams overlaid. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar common_words: The set of common words. Required. - :vartype common_words: list[str] - :ivar ignore_case: A value indicating whether common words matching will be case insensitive. - Default is false. - :vartype ignore_case: bool - :ivar use_query_mode: A value that indicates whether the token filter is in query mode. When in - query mode, the token filter generates bigrams and then removes common words and single terms - followed by a common word. Default is false. - :vartype use_query_mode: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "common_words": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "common_words": {"key": "commonWords", "type": "[str]"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - "use_query_mode": {"key": "queryMode", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - common_words: list[str], - ignore_case: bool = False, - use_query_mode: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword common_words: The set of common words. Required. - :paramtype common_words: list[str] - :keyword ignore_case: A value indicating whether common words matching will be case - insensitive. Default is false. - :paramtype ignore_case: bool - :keyword use_query_mode: A value that indicates whether the token filter is in query mode. When - in query mode, the token filter generates bigrams and then removes common words and single - terms followed by a common word. Default is false. - :paramtype use_query_mode: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CommonGramTokenFilter" - self.common_words = common_words - self.ignore_case = ignore_case - self.use_query_mode = use_query_mode - - -class CommonModelParameters(_serialization.Model): - """Common language model parameters for Chat Completions. If omitted, default values are used. - - :ivar model: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not - specified. - :vartype model: str - :ivar frequency_penalty: A float in the range [-2,2] that reduces or increases likelihood of - repeated tokens. Default is 0. - :vartype frequency_penalty: float - :ivar presence_penalty: A float in the range [-2,2] that penalizes new tokens based on their - existing presence. Default is 0. - :vartype presence_penalty: float - :ivar max_tokens: Maximum number of tokens to generate. - :vartype max_tokens: int - :ivar temperature: Sampling temperature. Default is 0.7. - :vartype temperature: float - :ivar seed: Random seed for controlling deterministic outputs. If omitted, randomization is - used. - :vartype seed: int - :ivar stop: List of stop sequences that will cut off text generation. Default is none. - :vartype stop: list[str] - """ - - _attribute_map = { - "model": {"key": "model", "type": "str"}, - "frequency_penalty": {"key": "frequencyPenalty", "type": "float"}, - "presence_penalty": {"key": "presencePenalty", "type": "float"}, - "max_tokens": {"key": "maxTokens", "type": "int"}, - "temperature": {"key": "temperature", "type": "float"}, - "seed": {"key": "seed", "type": "int"}, - "stop": {"key": "stop", "type": "[str]"}, - } - - def __init__( - self, - *, - model: Optional[str] = None, - frequency_penalty: float = 0, - presence_penalty: float = 0, - max_tokens: Optional[int] = None, - temperature: float = 0.7, - seed: Optional[int] = None, - stop: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword model: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not - specified. - :paramtype model: str - :keyword frequency_penalty: A float in the range [-2,2] that reduces or increases likelihood of - repeated tokens. Default is 0. - :paramtype frequency_penalty: float - :keyword presence_penalty: A float in the range [-2,2] that penalizes new tokens based on their - existing presence. Default is 0. - :paramtype presence_penalty: float - :keyword max_tokens: Maximum number of tokens to generate. - :paramtype max_tokens: int - :keyword temperature: Sampling temperature. Default is 0.7. - :paramtype temperature: float - :keyword seed: Random seed for controlling deterministic outputs. If omitted, randomization is - used. - :paramtype seed: int - :keyword stop: List of stop sequences that will cut off text generation. Default is none. - :paramtype stop: list[str] - """ - super().__init__(**kwargs) - self.model = model - self.frequency_penalty = frequency_penalty - self.presence_penalty = presence_penalty - self.max_tokens = max_tokens - self.temperature = temperature - self.seed = seed - self.stop = stop - - -class ConditionalSkill(SearchIndexerSkill): - """A skill that enables scenarios that require a Boolean operation to determine the data to assign - to an output. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.ConditionalSkill" - - -class CorsOptions(_serialization.Model): - """Defines options to control Cross-Origin Resource Sharing (CORS) for an index. - - All required parameters must be populated in order to send to server. - - :ivar allowed_origins: The list of origins from which JavaScript code will be granted access to - your index. Can contain a list of hosts of the form - {protocol}://{fully-qualified-domain-name}[:{port#}], or a single '*' to allow all origins (not - recommended). Required. - :vartype allowed_origins: list[str] - :ivar max_age_in_seconds: The duration for which browsers should cache CORS preflight - responses. Defaults to 5 minutes. - :vartype max_age_in_seconds: int - """ - - _validation = { - "allowed_origins": {"required": True}, - } - - _attribute_map = { - "allowed_origins": {"key": "allowedOrigins", "type": "[str]"}, - "max_age_in_seconds": {"key": "maxAgeInSeconds", "type": "int"}, - } - - def __init__(self, *, allowed_origins: list[str], max_age_in_seconds: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword allowed_origins: The list of origins from which JavaScript code will be granted access - to your index. Can contain a list of hosts of the form - {protocol}://{fully-qualified-domain-name}[:{port#}], or a single '*' to allow all origins (not - recommended). Required. - :paramtype allowed_origins: list[str] - :keyword max_age_in_seconds: The duration for which browsers should cache CORS preflight - responses. Defaults to 5 minutes. - :paramtype max_age_in_seconds: int - """ - super().__init__(**kwargs) - self.allowed_origins = allowed_origins - self.max_age_in_seconds = max_age_in_seconds - - -class LexicalAnalyzer(_serialization.Model): - """Base type for analyzers. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CustomAnalyzer, PatternAnalyzer, LuceneStandardAnalyzer, StopAnalyzer - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.CustomAnalyzer": "CustomAnalyzer", - "#Microsoft.Azure.Search.PatternAnalyzer": "PatternAnalyzer", - "#Microsoft.Azure.Search.StandardAnalyzer": "LuceneStandardAnalyzer", - "#Microsoft.Azure.Search.StopAnalyzer": "StopAnalyzer", - } - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class CustomAnalyzer(LexicalAnalyzer): - """Allows you to take control over the process of converting text into indexable/searchable - tokens. It's a user-defined configuration consisting of a single predefined tokenizer and one - or more filters. The tokenizer is responsible for breaking text into tokens, and the filters - for modifying tokens emitted by the tokenizer. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar tokenizer: The name of the tokenizer to use to divide continuous text into a sequence of - tokens, such as breaking a sentence into words. Required. Known values are: "classic", - "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", - "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", - "standard_v2", "uax_url_email", and "whitespace". - :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar token_filters: A list of token filters used to filter out or modify the tokens generated - by a tokenizer. For example, you can specify a lowercase filter that converts all characters to - lowercase. The filters are run in the order in which they are listed. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: A list of character filters used to prepare input text before it is - processed by the tokenizer. For instance, they can replace certain characters or symbols. The - filters are run in the order in which they are listed. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "tokenizer": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "tokenizer": {"key": "tokenizer", "type": "str"}, - "token_filters": {"key": "tokenFilters", "type": "[str]"}, - "char_filters": {"key": "charFilters", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - tokenizer: Union[str, "_models.LexicalTokenizerName"], - token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, - char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword tokenizer: The name of the tokenizer to use to divide continuous text into a sequence - of tokens, such as breaking a sentence into words. Required. Known values are: "classic", - "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", - "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", - "standard_v2", "uax_url_email", and "whitespace". - :paramtype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :keyword token_filters: A list of token filters used to filter out or modify the tokens - generated by a tokenizer. For example, you can specify a lowercase filter that converts all - characters to lowercase. The filters are run in the order in which they are listed. - :paramtype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: A list of character filters used to prepare input text before it is - processed by the tokenizer. For instance, they can replace certain characters or symbols. The - filters are run in the order in which they are listed. - :paramtype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CustomAnalyzer" - self.tokenizer = tokenizer - self.token_filters = token_filters - self.char_filters = char_filters - - -class CustomEntity(_serialization.Model): - """An object that contains information about the matches that were found, and related metadata. - - All required parameters must be populated in order to send to server. - - :ivar name: The top-level entity descriptor. Matches in the skill output will be grouped by - this name, and it should represent the "normalized" form of the text being found. Required. - :vartype name: str - :ivar description: This field can be used as a passthrough for custom metadata about the - matched text(s). The value of this field will appear with every match of its entity in the - skill output. - :vartype description: str - :ivar type: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :vartype type: str - :ivar subtype: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :vartype subtype: str - :ivar id: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :vartype id: str - :ivar case_sensitive: Defaults to false. Boolean value denoting whether comparisons with the - entity name should be sensitive to character casing. Sample case insensitive matches of - "Microsoft" could be: microsoft, microSoft, MICROSOFT. - :vartype case_sensitive: bool - :ivar accent_sensitive: Defaults to false. Boolean value denoting whether comparisons with the - entity name should be sensitive to accent. - :vartype accent_sensitive: bool - :ivar fuzzy_edit_distance: Defaults to 0. Maximum value of 5. Denotes the acceptable number of - divergent characters that would still constitute a match with the entity name. The smallest - possible fuzziness for any given match is returned. For instance, if the edit distance is set - to 3, "Windows10" would still match "Windows", "Windows10" and "Windows 7". When case - sensitivity is set to false, case differences do NOT count towards fuzziness tolerance, but - otherwise do. - :vartype fuzzy_edit_distance: int - :ivar default_case_sensitive: Changes the default case sensitivity value for this entity. It be - used to change the default value of all aliases caseSensitive values. - :vartype default_case_sensitive: bool - :ivar default_accent_sensitive: Changes the default accent sensitivity value for this entity. - It be used to change the default value of all aliases accentSensitive values. - :vartype default_accent_sensitive: bool - :ivar default_fuzzy_edit_distance: Changes the default fuzzy edit distance value for this - entity. It can be used to change the default value of all aliases fuzzyEditDistance values. - :vartype default_fuzzy_edit_distance: int - :ivar aliases: An array of complex objects that can be used to specify alternative spellings or - synonyms to the root entity name. - :vartype aliases: list[~azure.search.documents.indexes.models.CustomEntityAlias] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "subtype": {"key": "subtype", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "case_sensitive": {"key": "caseSensitive", "type": "bool"}, - "accent_sensitive": {"key": "accentSensitive", "type": "bool"}, - "fuzzy_edit_distance": {"key": "fuzzyEditDistance", "type": "int"}, - "default_case_sensitive": {"key": "defaultCaseSensitive", "type": "bool"}, - "default_accent_sensitive": {"key": "defaultAccentSensitive", "type": "bool"}, - "default_fuzzy_edit_distance": {"key": "defaultFuzzyEditDistance", "type": "int"}, - "aliases": {"key": "aliases", "type": "[CustomEntityAlias]"}, - } - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - type: Optional[str] = None, - subtype: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - case_sensitive: Optional[bool] = None, - accent_sensitive: Optional[bool] = None, - fuzzy_edit_distance: Optional[int] = None, - default_case_sensitive: Optional[bool] = None, - default_accent_sensitive: Optional[bool] = None, - default_fuzzy_edit_distance: Optional[int] = None, - aliases: Optional[list["_models.CustomEntityAlias"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The top-level entity descriptor. Matches in the skill output will be grouped by - this name, and it should represent the "normalized" form of the text being found. Required. - :paramtype name: str - :keyword description: This field can be used as a passthrough for custom metadata about the - matched text(s). The value of this field will appear with every match of its entity in the - skill output. - :paramtype description: str - :keyword type: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :paramtype type: str - :keyword subtype: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :paramtype subtype: str - :keyword id: This field can be used as a passthrough for custom metadata about the matched - text(s). The value of this field will appear with every match of its entity in the skill - output. - :paramtype id: str - :keyword case_sensitive: Defaults to false. Boolean value denoting whether comparisons with the - entity name should be sensitive to character casing. Sample case insensitive matches of - "Microsoft" could be: microsoft, microSoft, MICROSOFT. - :paramtype case_sensitive: bool - :keyword accent_sensitive: Defaults to false. Boolean value denoting whether comparisons with - the entity name should be sensitive to accent. - :paramtype accent_sensitive: bool - :keyword fuzzy_edit_distance: Defaults to 0. Maximum value of 5. Denotes the acceptable number - of divergent characters that would still constitute a match with the entity name. The smallest - possible fuzziness for any given match is returned. For instance, if the edit distance is set - to 3, "Windows10" would still match "Windows", "Windows10" and "Windows 7". When case - sensitivity is set to false, case differences do NOT count towards fuzziness tolerance, but - otherwise do. - :paramtype fuzzy_edit_distance: int - :keyword default_case_sensitive: Changes the default case sensitivity value for this entity. It - be used to change the default value of all aliases caseSensitive values. - :paramtype default_case_sensitive: bool - :keyword default_accent_sensitive: Changes the default accent sensitivity value for this - entity. It be used to change the default value of all aliases accentSensitive values. - :paramtype default_accent_sensitive: bool - :keyword default_fuzzy_edit_distance: Changes the default fuzzy edit distance value for this - entity. It can be used to change the default value of all aliases fuzzyEditDistance values. - :paramtype default_fuzzy_edit_distance: int - :keyword aliases: An array of complex objects that can be used to specify alternative spellings - or synonyms to the root entity name. - :paramtype aliases: list[~azure.search.documents.indexes.models.CustomEntityAlias] - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.type = type - self.subtype = subtype - self.id = id - self.case_sensitive = case_sensitive - self.accent_sensitive = accent_sensitive - self.fuzzy_edit_distance = fuzzy_edit_distance - self.default_case_sensitive = default_case_sensitive - self.default_accent_sensitive = default_accent_sensitive - self.default_fuzzy_edit_distance = default_fuzzy_edit_distance - self.aliases = aliases - - -class CustomEntityAlias(_serialization.Model): - """A complex object that can be used to specify alternative spellings or synonyms to the root - entity name. - - All required parameters must be populated in order to send to server. - - :ivar text: The text of the alias. Required. - :vartype text: str - :ivar case_sensitive: Determine if the alias is case sensitive. - :vartype case_sensitive: bool - :ivar accent_sensitive: Determine if the alias is accent sensitive. - :vartype accent_sensitive: bool - :ivar fuzzy_edit_distance: Determine the fuzzy edit distance of the alias. - :vartype fuzzy_edit_distance: int - """ - - _validation = { - "text": {"required": True}, - } - - _attribute_map = { - "text": {"key": "text", "type": "str"}, - "case_sensitive": {"key": "caseSensitive", "type": "bool"}, - "accent_sensitive": {"key": "accentSensitive", "type": "bool"}, - "fuzzy_edit_distance": {"key": "fuzzyEditDistance", "type": "int"}, - } - - def __init__( - self, - *, - text: str, - case_sensitive: Optional[bool] = None, - accent_sensitive: Optional[bool] = None, - fuzzy_edit_distance: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword text: The text of the alias. Required. - :paramtype text: str - :keyword case_sensitive: Determine if the alias is case sensitive. - :paramtype case_sensitive: bool - :keyword accent_sensitive: Determine if the alias is accent sensitive. - :paramtype accent_sensitive: bool - :keyword fuzzy_edit_distance: Determine the fuzzy edit distance of the alias. - :paramtype fuzzy_edit_distance: int - """ - super().__init__(**kwargs) - self.text = text - self.case_sensitive = case_sensitive - self.accent_sensitive = accent_sensitive - self.fuzzy_edit_distance = fuzzy_edit_distance - - -class CustomEntityLookupSkill(SearchIndexerSkill): - """A skill looks for text from a custom, user-defined list of words and phrases. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "de", "en", "es", "fi", "fr", "it", "ko", and "pt". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage - :ivar entities_definition_uri: Path to a JSON or CSV file containing all the target text to - match against. This entity definition is read at the beginning of an indexer run. Any updates - to this file during an indexer run will not take effect until subsequent runs. This config must - be accessible over HTTPS. - :vartype entities_definition_uri: str - :ivar inline_entities_definition: The inline CustomEntity definition. - :vartype inline_entities_definition: list[~azure.search.documents.indexes.models.CustomEntity] - :ivar global_default_case_sensitive: A global flag for CaseSensitive. If CaseSensitive is not - set in CustomEntity, this value will be the default value. - :vartype global_default_case_sensitive: bool - :ivar global_default_accent_sensitive: A global flag for AccentSensitive. If AccentSensitive is - not set in CustomEntity, this value will be the default value. - :vartype global_default_accent_sensitive: bool - :ivar global_default_fuzzy_edit_distance: A global flag for FuzzyEditDistance. If - FuzzyEditDistance is not set in CustomEntity, this value will be the default value. - :vartype global_default_fuzzy_edit_distance: int - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "entities_definition_uri": {"key": "entitiesDefinitionUri", "type": "str"}, - "inline_entities_definition": {"key": "inlineEntitiesDefinition", "type": "[CustomEntity]"}, - "global_default_case_sensitive": {"key": "globalDefaultCaseSensitive", "type": "bool"}, - "global_default_accent_sensitive": {"key": "globalDefaultAccentSensitive", "type": "bool"}, - "global_default_fuzzy_edit_distance": {"key": "globalDefaultFuzzyEditDistance", "type": "int"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.CustomEntityLookupSkillLanguage"]] = None, - entities_definition_uri: Optional[str] = None, - inline_entities_definition: Optional[list["_models.CustomEntity"]] = None, - global_default_case_sensitive: Optional[bool] = None, - global_default_accent_sensitive: Optional[bool] = None, - global_default_fuzzy_edit_distance: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "da", "de", "en", "es", "fi", "fr", "it", "ko", and "pt". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage - :keyword entities_definition_uri: Path to a JSON or CSV file containing all the target text to - match against. This entity definition is read at the beginning of an indexer run. Any updates - to this file during an indexer run will not take effect until subsequent runs. This config must - be accessible over HTTPS. - :paramtype entities_definition_uri: str - :keyword inline_entities_definition: The inline CustomEntity definition. - :paramtype inline_entities_definition: - list[~azure.search.documents.indexes.models.CustomEntity] - :keyword global_default_case_sensitive: A global flag for CaseSensitive. If CaseSensitive is - not set in CustomEntity, this value will be the default value. - :paramtype global_default_case_sensitive: bool - :keyword global_default_accent_sensitive: A global flag for AccentSensitive. If AccentSensitive - is not set in CustomEntity, this value will be the default value. - :paramtype global_default_accent_sensitive: bool - :keyword global_default_fuzzy_edit_distance: A global flag for FuzzyEditDistance. If - FuzzyEditDistance is not set in CustomEntity, this value will be the default value. - :paramtype global_default_fuzzy_edit_distance: int - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.CustomEntityLookupSkill" - self.default_language_code = default_language_code - self.entities_definition_uri = entities_definition_uri - self.inline_entities_definition = inline_entities_definition - self.global_default_case_sensitive = global_default_case_sensitive - self.global_default_accent_sensitive = global_default_accent_sensitive - self.global_default_fuzzy_edit_distance = global_default_fuzzy_edit_distance - - -class LexicalNormalizer(_serialization.Model): - """Base type for normalizers. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CustomNormalizer - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of normalizer. Required. - :vartype odata_type: str - :ivar name: The name of the normalizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :vartype name: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - } - - _subtype_map = {"odata_type": {"#Microsoft.Azure.Search.CustomNormalizer": "CustomNormalizer"}} - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the normalizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.name = name - - -class CustomNormalizer(LexicalNormalizer): - """Allows you to configure normalization for filterable, sortable, and facetable fields, which by - default operate with strict matching. This is a user-defined configuration consisting of at - least one or more filters, which modify the token that is stored. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of normalizer. Required. - :vartype odata_type: str - :ivar name: The name of the normalizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :vartype name: str - :ivar token_filters: A list of token filters used to filter out or modify the input token. For - example, you can specify a lowercase filter that converts all characters to lowercase. The - filters are run in the order in which they are listed. - :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: A list of character filters used to prepare input text before it is - processed. For instance, they can replace certain characters or symbols. The filters are run in - the order in which they are listed. - :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "token_filters": {"key": "tokenFilters", "type": "[str]"}, - "char_filters": {"key": "charFilters", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, - char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the normalizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. It cannot end in '.microsoft' nor '.lucene', nor be named 'asciifolding', - 'standard', 'lowercase', 'uppercase', or 'elision'. Required. - :paramtype name: str - :keyword token_filters: A list of token filters used to filter out or modify the input token. - For example, you can specify a lowercase filter that converts all characters to lowercase. The - filters are run in the order in which they are listed. - :paramtype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: A list of character filters used to prepare input text before it is - processed. For instance, they can replace certain characters or symbols. The filters are run in - the order in which they are listed. - :paramtype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.CustomNormalizer" - self.token_filters = token_filters - self.char_filters = char_filters - - -class DataChangeDetectionPolicy(_serialization.Model): - """Base type for data change detection policies. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - HighWaterMarkChangeDetectionPolicy, SqlIntegratedChangeTrackingPolicy - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy": "HighWaterMarkChangeDetectionPolicy", - "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy": "SqlIntegratedChangeTrackingPolicy", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class DataDeletionDetectionPolicy(_serialization.Model): - """Base type for data deletion detection policies. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - NativeBlobSoftDeleteDeletionDetectionPolicy, SoftDeleteColumnDeletionDetectionPolicy - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. - Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy": "NativeBlobSoftDeleteDeletionDetectionPolicy", - "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy": "SoftDeleteColumnDeletionDetectionPolicy", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class DataSourceCredentials(_serialization.Model): - """Represents credentials that can be used to connect to a datasource. - - :ivar connection_string: The connection string for the datasource. Set to ```` (with - brackets) if you don't want the connection string updated. Set to ```` if you want to - remove the connection string value from the datasource. - :vartype connection_string: str - """ - - _attribute_map = { - "connection_string": {"key": "connectionString", "type": "str"}, - } - - def __init__(self, *, connection_string: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword connection_string: The connection string for the datasource. Set to ```` - (with brackets) if you don't want the connection string updated. Set to ```` if you - want to remove the connection string value from the datasource. - :paramtype connection_string: str - """ - super().__init__(**kwargs) - self.connection_string = connection_string - - -class DefaultCognitiveServicesAccount(CognitiveServicesAccount): - """An empty object that represents the default Azure AI service resource for a skillset. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a - skillset. Required. - :vartype odata_type: str - :ivar description: Description of the Azure AI service resource attached to a skillset. - :vartype description: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__(self, *, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword description: Description of the Azure AI service resource attached to a skillset. - :paramtype description: str - """ - super().__init__(description=description, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DefaultCognitiveServices" - - -class DictionaryDecompounderTokenFilter(TokenFilter): - """Decomposes compound words found in many Germanic languages. This token filter is implemented - using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar word_list: The list of words to match against. Required. - :vartype word_list: list[str] - :ivar min_word_size: The minimum word size. Only words longer than this get processed. Default - is 5. Maximum is 300. - :vartype min_word_size: int - :ivar min_subword_size: The minimum subword size. Only subwords longer than this are outputted. - Default is 2. Maximum is 300. - :vartype min_subword_size: int - :ivar max_subword_size: The maximum subword size. Only subwords shorter than this are - outputted. Default is 15. Maximum is 300. - :vartype max_subword_size: int - :ivar only_longest_match: A value indicating whether to add only the longest matching subword - to the output. Default is false. - :vartype only_longest_match: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "word_list": {"required": True}, - "min_word_size": {"maximum": 300}, - "min_subword_size": {"maximum": 300}, - "max_subword_size": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "word_list": {"key": "wordList", "type": "[str]"}, - "min_word_size": {"key": "minWordSize", "type": "int"}, - "min_subword_size": {"key": "minSubwordSize", "type": "int"}, - "max_subword_size": {"key": "maxSubwordSize", "type": "int"}, - "only_longest_match": {"key": "onlyLongestMatch", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - word_list: list[str], - min_word_size: int = 5, - min_subword_size: int = 2, - max_subword_size: int = 15, - only_longest_match: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword word_list: The list of words to match against. Required. - :paramtype word_list: list[str] - :keyword min_word_size: The minimum word size. Only words longer than this get processed. - Default is 5. Maximum is 300. - :paramtype min_word_size: int - :keyword min_subword_size: The minimum subword size. Only subwords longer than this are - outputted. Default is 2. Maximum is 300. - :paramtype min_subword_size: int - :keyword max_subword_size: The maximum subword size. Only subwords shorter than this are - outputted. Default is 15. Maximum is 300. - :paramtype max_subword_size: int - :keyword only_longest_match: A value indicating whether to add only the longest matching - subword to the output. Default is false. - :paramtype only_longest_match: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter" - self.word_list = word_list - self.min_word_size = min_word_size - self.min_subword_size = min_subword_size - self.max_subword_size = max_subword_size - self.only_longest_match = only_longest_match - - -class ScoringFunction(_serialization.Model): - """Base type for functions that can modify document scores during ranking. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - DistanceScoringFunction, FreshnessScoringFunction, MagnitudeScoringFunction, TagScoringFunction - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - } - - _subtype_map = { - "type": { - "distance": "DistanceScoringFunction", - "freshness": "FreshnessScoringFunction", - "magnitude": "MagnitudeScoringFunction", - "tag": "TagScoringFunction", - } - } - - def __init__( - self, - *, - field_name: str, - boost: float, - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.field_name = field_name - self.boost = boost - self.interpolation = interpolation - - -class DistanceScoringFunction(ScoringFunction): - """Defines a function that boosts scores based on distance from a geographic location. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the distance scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.DistanceScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "distance", "type": "DistanceScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.DistanceScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the distance scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.DistanceScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "distance" - self.parameters = parameters - - -class DistanceScoringParameters(_serialization.Model): - """Provides parameter values to a distance scoring function. - - All required parameters must be populated in order to send to server. - - :ivar reference_point_parameter: The name of the parameter passed in search queries to specify - the reference location. Required. - :vartype reference_point_parameter: str - :ivar boosting_distance: The distance in kilometers from the reference location where the - boosting range ends. Required. - :vartype boosting_distance: float - """ - - _validation = { - "reference_point_parameter": {"required": True}, - "boosting_distance": {"required": True}, - } - - _attribute_map = { - "reference_point_parameter": {"key": "referencePointParameter", "type": "str"}, - "boosting_distance": {"key": "boostingDistance", "type": "float"}, - } - - def __init__(self, *, reference_point_parameter: str, boosting_distance: float, **kwargs: Any) -> None: - """ - :keyword reference_point_parameter: The name of the parameter passed in search queries to - specify the reference location. Required. - :paramtype reference_point_parameter: str - :keyword boosting_distance: The distance in kilometers from the reference location where the - boosting range ends. Required. - :paramtype boosting_distance: float - """ - super().__init__(**kwargs) - self.reference_point_parameter = reference_point_parameter - self.boosting_distance = boosting_distance - - -class DocumentExtractionSkill(SearchIndexerSkill): - """A skill that extracts content from a file within the enrichment pipeline. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar parsing_mode: The parsingMode for the skill. Will be set to 'default' if not defined. - :vartype parsing_mode: str - :ivar data_to_extract: The type of data to be extracted for the skill. Will be set to - 'contentAndMetadata' if not defined. - :vartype data_to_extract: str - :ivar configuration: A dictionary of configurations for the skill. - :vartype configuration: dict[str, any] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "parsing_mode": {"key": "parsingMode", "type": "str"}, - "data_to_extract": {"key": "dataToExtract", "type": "str"}, - "configuration": {"key": "configuration", "type": "{object}"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - parsing_mode: Optional[str] = None, - data_to_extract: Optional[str] = None, - configuration: Optional[dict[str, Any]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword parsing_mode: The parsingMode for the skill. Will be set to 'default' if not defined. - :paramtype parsing_mode: str - :keyword data_to_extract: The type of data to be extracted for the skill. Will be set to - 'contentAndMetadata' if not defined. - :paramtype data_to_extract: str - :keyword configuration: A dictionary of configurations for the skill. - :paramtype configuration: dict[str, any] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.DocumentExtractionSkill" - self.parsing_mode = parsing_mode - self.data_to_extract = data_to_extract - self.configuration = configuration - - -class DocumentIntelligenceLayoutSkill(SearchIndexerSkill): - """A skill that extracts content and layout information, via Azure AI Services, from files within - the enrichment pipeline. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar output_format: Controls the cardinality of the output format. Default is 'markdown'. - Known values are: "text" and "markdown". - :vartype output_format: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat - :ivar output_mode: Controls the cardinality of the output produced by the skill. Default is - 'oneToMany'. "oneToMany" - :vartype output_mode: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode - :ivar markdown_header_depth: The depth of headers in the markdown output. Default is h6. Known - values are: "h1", "h2", "h3", "h4", "h5", and "h6". - :vartype markdown_header_depth: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth - :ivar extraction_options: Controls the cardinality of the content extracted from the document - by the skill. - :vartype extraction_options: list[str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions] - :ivar chunking_properties: Controls the cardinality for chunking the content. - :vartype chunking_properties: - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "output_format": {"key": "outputFormat", "type": "str"}, - "output_mode": {"key": "outputMode", "type": "str"}, - "markdown_header_depth": {"key": "markdownHeaderDepth", "type": "str"}, - "extraction_options": {"key": "extractionOptions", "type": "[str]"}, - "chunking_properties": { - "key": "chunkingProperties", - "type": "DocumentIntelligenceLayoutSkillChunkingProperties", - }, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - output_format: Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"] = "markdown", - output_mode: Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"] = "oneToMany", - markdown_header_depth: Union[str, "_models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth"] = "h6", - extraction_options: Optional[ - list[Union[str, "_models.DocumentIntelligenceLayoutSkillExtractionOptions"]] - ] = None, - chunking_properties: Optional["_models.DocumentIntelligenceLayoutSkillChunkingProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword output_format: Controls the cardinality of the output format. Default is 'markdown'. - Known values are: "text" and "markdown". - :paramtype output_format: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat - :keyword output_mode: Controls the cardinality of the output produced by the skill. Default is - 'oneToMany'. "oneToMany" - :paramtype output_mode: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode - :keyword markdown_header_depth: The depth of headers in the markdown output. Default is h6. - Known values are: "h1", "h2", "h3", "h4", "h5", and "h6". - :paramtype markdown_header_depth: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth - :keyword extraction_options: Controls the cardinality of the content extracted from the - document by the skill. - :paramtype extraction_options: list[str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions] - :keyword chunking_properties: Controls the cardinality for chunking the content. - :paramtype chunking_properties: - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill" - self.output_format = output_format - self.output_mode = output_mode - self.markdown_header_depth = markdown_header_depth - self.extraction_options = extraction_options - self.chunking_properties = chunking_properties - - -class DocumentIntelligenceLayoutSkillChunkingProperties(_serialization.Model): # pylint: disable=name-too-long - """Controls the cardinality for chunking the content. - - :ivar unit: The unit of the chunk. "characters" - :vartype unit: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit - :ivar maximum_length: The maximum chunk length in characters. Default is 500. - :vartype maximum_length: int - :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. - :vartype overlap_length: int - """ - - _attribute_map = { - "unit": {"key": "unit", "type": "str"}, - "maximum_length": {"key": "maximumLength", "type": "int"}, - "overlap_length": {"key": "overlapLength", "type": "int"}, - } - - def __init__( - self, - *, - unit: Union[str, "_models.DocumentIntelligenceLayoutSkillChunkingUnit"] = "characters", - maximum_length: Optional[int] = None, - overlap_length: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword unit: The unit of the chunk. "characters" - :paramtype unit: str or - ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit - :keyword maximum_length: The maximum chunk length in characters. Default is 500. - :paramtype maximum_length: int - :keyword overlap_length: The length of overlap provided between two text chunks. Default is 0. - :paramtype overlap_length: int - """ - super().__init__(**kwargs) - self.unit = unit - self.maximum_length = maximum_length - self.overlap_length = overlap_length - - -class DocumentKeysOrIds(_serialization.Model): - """DocumentKeysOrIds. - - :ivar document_keys: document keys to be reset. - :vartype document_keys: list[str] - :ivar datasource_document_ids: datasource document identifiers to be reset. - :vartype datasource_document_ids: list[str] - """ - - _attribute_map = { - "document_keys": {"key": "documentKeys", "type": "[str]"}, - "datasource_document_ids": {"key": "datasourceDocumentIds", "type": "[str]"}, - } - - def __init__( - self, - *, - document_keys: Optional[list[str]] = None, - datasource_document_ids: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword document_keys: document keys to be reset. - :paramtype document_keys: list[str] - :keyword datasource_document_ids: datasource document identifiers to be reset. - :paramtype datasource_document_ids: list[str] - """ - super().__init__(**kwargs) - self.document_keys = document_keys - self.datasource_document_ids = datasource_document_ids - - -class EdgeNGramTokenFilter(TokenFilter): - """Generates n-grams of the given size(s) starting from the front or the back of an input token. - This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. - :vartype max_gram: int - :ivar side: Specifies which side of the input the n-gram should be generated from. Default is - "front". Known values are: "front" and "back". - :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "side": {"key": "side", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. - :paramtype max_gram: int - :keyword side: Specifies which side of the input the n-gram should be generated from. Default - is "front". Known values are: "front" and "back". - :paramtype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.EdgeNGramTokenFilter" - self.min_gram = min_gram - self.max_gram = max_gram - self.side = side - - -class EdgeNGramTokenFilterV2(TokenFilter): - """Generates n-grams of the given size(s) starting from the front or the back of an input token. - This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - :ivar side: Specifies which side of the input the n-gram should be generated from. Default is - "front". Known values are: "front" and "back". - :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "side": {"key": "side", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - :keyword side: Specifies which side of the input the n-gram should be generated from. Default - is "front". Known values are: "front" and "back". - :paramtype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2" - self.min_gram = min_gram - self.max_gram = max_gram - self.side = side - - -class EdgeNGramTokenizer(LexicalTokenizer): - """Tokenizes the input from an edge into n-grams of the given size(s). This tokenizer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - :ivar token_chars: Character classes to keep in the tokens. - :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "token_chars": {"key": "tokenChars", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - :keyword token_chars: Character classes to keep in the tokens. - :paramtype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.EdgeNGramTokenizer" - self.min_gram = min_gram - self.max_gram = max_gram - self.token_chars = token_chars - - -class ElisionTokenFilter(TokenFilter): - """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). This - token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar articles: The set of articles to remove. - :vartype articles: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "articles": {"key": "articles", "type": "[str]"}, - } - - def __init__(self, *, name: str, articles: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword articles: The set of articles to remove. - :paramtype articles: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ElisionTokenFilter" - self.articles = articles - - -class EntityLinkingSkill(SearchIndexerSkill): - """Using the Text Analytics API, extracts linked entities from text. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[str] = None, - minimum_precision: Optional[float] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.V3.EntityLinkingSkill" - self.default_language_code = default_language_code - self.minimum_precision = minimum_precision - self.model_version = model_version - - -class EntityRecognitionSkill(SearchIndexerSkill): - """This skill is deprecated. Use the V3.EntityRecognitionSkill instead. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar categories: A list of entity categories that should be extracted. - :vartype categories: list[str or ~azure.search.documents.indexes.models.EntityCategory] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", "el", - "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", and "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage - :ivar include_typeless_entities: Determines whether or not to include entities which are well - known but don't conform to a pre-defined type. If this configuration is not set (default), set - to null or set to false, entities which don't conform to one of the pre-defined types will not - be surfaced. - :vartype include_typeless_entities: bool - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "categories": {"key": "categories", "type": "[str]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_typeless_entities": {"key": "includeTypelessEntities", "type": "bool"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - categories: Optional[list[Union[str, "_models.EntityCategory"]]] = None, - default_language_code: Optional[Union[str, "_models.EntityRecognitionSkillLanguage"]] = None, - include_typeless_entities: Optional[bool] = None, - minimum_precision: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword categories: A list of entity categories that should be extracted. - :paramtype categories: list[str or ~azure.search.documents.indexes.models.EntityCategory] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", - "el", "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", and "tr". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage - :keyword include_typeless_entities: Determines whether or not to include entities which are - well known but don't conform to a pre-defined type. If this configuration is not set (default), - set to null or set to false, entities which don't conform to one of the pre-defined types will - not be surfaced. - :paramtype include_typeless_entities: bool - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.EntityRecognitionSkill" - self.categories = categories - self.default_language_code = default_language_code - self.include_typeless_entities = include_typeless_entities - self.minimum_precision = minimum_precision - - -class EntityRecognitionSkillV3(SearchIndexerSkill): - """Using the Text Analytics API, extracts entities of different types from text. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar categories: A list of entity categories that should be extracted. - :vartype categories: list[str] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar model_version: The version of the model to use when calling the Text Analytics API. It - will default to the latest available when not specified. We recommend you do not specify this - value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "categories": {"key": "categories", "type": "[str]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - categories: Optional[list[str]] = None, - default_language_code: Optional[str] = None, - minimum_precision: Optional[float] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword categories: A list of entity categories that should be extracted. - :paramtype categories: list[str] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - :keyword model_version: The version of the model to use when calling the Text Analytics API. It - will default to the latest available when not specified. We recommend you do not specify this - value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill" - self.categories = categories - self.default_language_code = default_language_code - self.minimum_precision = minimum_precision - self.model_version = model_version - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.info: Optional[JSON] = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.search.documents.indexes.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.search.documents.indexes.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code: Optional[str] = None - self.message: Optional[str] = None - self.target: Optional[str] = None - self.details: Optional[list["_models.ErrorDetail"]] = None - self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.search.documents.indexes.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.search.documents.indexes.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class VectorSearchAlgorithmConfiguration(_serialization.Model): - """Contains configuration options specific to the algorithm used during indexing or querying. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ExhaustiveKnnAlgorithmConfiguration, HnswAlgorithmConfiguration - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular configuration. Required. - :vartype name: str - :ivar kind: The name of the kind of algorithm being configured for use with vector search. - Required. Known values are: "hnsw" and "exhaustiveKnn". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = { - "kind": {"exhaustiveKnn": "ExhaustiveKnnAlgorithmConfiguration", "hnsw": "HnswAlgorithmConfiguration"} - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name to associate with this particular configuration. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - self.kind: Optional[str] = None - - -class ExhaustiveKnnAlgorithmConfiguration(VectorSearchAlgorithmConfiguration): - """Contains configuration options specific to the exhaustive KNN algorithm used during querying, - which will perform brute-force search across the entire vector index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular configuration. Required. - :vartype name: str - :ivar kind: The name of the kind of algorithm being configured for use with vector search. - Required. Known values are: "hnsw" and "exhaustiveKnn". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind - :ivar parameters: Contains the parameters specific to exhaustive KNN algorithm. - :vartype parameters: ~azure.search.documents.indexes.models.ExhaustiveKnnParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "parameters": {"key": "exhaustiveKnnParameters", "type": "ExhaustiveKnnParameters"}, - } - - def __init__( - self, *, name: str, parameters: Optional["_models.ExhaustiveKnnParameters"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: The name to associate with this particular configuration. Required. - :paramtype name: str - :keyword parameters: Contains the parameters specific to exhaustive KNN algorithm. - :paramtype parameters: ~azure.search.documents.indexes.models.ExhaustiveKnnParameters - """ - super().__init__(name=name, **kwargs) - self.kind: str = "exhaustiveKnn" - self.parameters = parameters - - -class ExhaustiveKnnParameters(_serialization.Model): - """Contains the parameters specific to exhaustive KNN algorithm. - - :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", - "euclidean", "dotProduct", and "hamming". - :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - - _attribute_map = { - "metric": {"key": "metric", "type": "str"}, - } - - def __init__( - self, *, metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, **kwargs: Any - ) -> None: - """ - :keyword metric: The similarity metric to use for vector comparisons. Known values are: - "cosine", "euclidean", "dotProduct", and "hamming". - :paramtype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - super().__init__(**kwargs) - self.metric = metric - - -class FieldMapping(_serialization.Model): - """Defines a mapping between a field in a data source and a target field in an index. - - All required parameters must be populated in order to send to server. - - :ivar source_field_name: The name of the field in the data source. Required. - :vartype source_field_name: str - :ivar target_field_name: The name of the target field in the index. Same as the source field - name by default. - :vartype target_field_name: str - :ivar mapping_function: A function to apply to each source field value before indexing. - :vartype mapping_function: ~azure.search.documents.indexes.models.FieldMappingFunction - """ - - _validation = { - "source_field_name": {"required": True}, - } - - _attribute_map = { - "source_field_name": {"key": "sourceFieldName", "type": "str"}, - "target_field_name": {"key": "targetFieldName", "type": "str"}, - "mapping_function": {"key": "mappingFunction", "type": "FieldMappingFunction"}, - } - - def __init__( - self, - *, - source_field_name: str, - target_field_name: Optional[str] = None, - mapping_function: Optional["_models.FieldMappingFunction"] = None, - **kwargs: Any - ) -> None: - """ - :keyword source_field_name: The name of the field in the data source. Required. - :paramtype source_field_name: str - :keyword target_field_name: The name of the target field in the index. Same as the source field - name by default. - :paramtype target_field_name: str - :keyword mapping_function: A function to apply to each source field value before indexing. - :paramtype mapping_function: ~azure.search.documents.indexes.models.FieldMappingFunction - """ - super().__init__(**kwargs) - self.source_field_name = source_field_name - self.target_field_name = target_field_name - self.mapping_function = mapping_function - - -class FieldMappingFunction(_serialization.Model): - """Represents a function that transforms a value from a data source before indexing. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the field mapping function. Required. - :vartype name: str - :ivar parameters: A dictionary of parameter name/value pairs to pass to the function. Each - value must be of a primitive type. - :vartype parameters: dict[str, any] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "parameters": {"key": "parameters", "type": "{object}"}, - } - - def __init__(self, *, name: str, parameters: Optional[dict[str, Any]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the field mapping function. Required. - :paramtype name: str - :keyword parameters: A dictionary of parameter name/value pairs to pass to the function. Each - value must be of a primitive type. - :paramtype parameters: dict[str, any] - """ - super().__init__(**kwargs) - self.name = name - self.parameters = parameters - - -class FreshnessScoringFunction(ScoringFunction): - """Defines a function that boosts scores based on the value of a date-time field. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the freshness scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.FreshnessScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "freshness", "type": "FreshnessScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.FreshnessScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the freshness scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.FreshnessScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "freshness" - self.parameters = parameters - - -class FreshnessScoringParameters(_serialization.Model): - """Provides parameter values to a freshness scoring function. - - All required parameters must be populated in order to send to server. - - :ivar boosting_duration: The expiration period after which boosting will stop for a particular - document. Required. - :vartype boosting_duration: ~datetime.timedelta - """ - - _validation = { - "boosting_duration": {"required": True}, - } - - _attribute_map = { - "boosting_duration": {"key": "boostingDuration", "type": "duration"}, - } - - def __init__(self, *, boosting_duration: datetime.timedelta, **kwargs: Any) -> None: - """ - :keyword boosting_duration: The expiration period after which boosting will stop for a - particular document. Required. - :paramtype boosting_duration: ~datetime.timedelta - """ - super().__init__(**kwargs) - self.boosting_duration = boosting_duration - - -class GetIndexStatisticsResult(_serialization.Model): - """Statistics for a given index. Statistics are collected periodically and are not guaranteed to - always be up-to-date. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar document_count: The number of documents in the index. Required. - :vartype document_count: int - :ivar storage_size: The amount of storage in bytes consumed by the index. Required. - :vartype storage_size: int - :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. - Required. - :vartype vector_index_size: int - """ - - _validation = { - "document_count": {"required": True, "readonly": True}, - "storage_size": {"required": True, "readonly": True}, - "vector_index_size": {"required": True, "readonly": True}, - } - - _attribute_map = { - "document_count": {"key": "documentCount", "type": "int"}, - "storage_size": {"key": "storageSize", "type": "int"}, - "vector_index_size": {"key": "vectorIndexSize", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.document_count: Optional[int] = None - self.storage_size: Optional[int] = None - self.vector_index_size: Optional[int] = None - - -class HighWaterMarkChangeDetectionPolicy(DataChangeDetectionPolicy): - """Defines a data change detection policy that captures changes based on the value of a high water - mark column. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. - :vartype odata_type: str - :ivar high_water_mark_column_name: The name of the high water mark column. Required. - :vartype high_water_mark_column_name: str - """ - - _validation = { - "odata_type": {"required": True}, - "high_water_mark_column_name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "high_water_mark_column_name": {"key": "highWaterMarkColumnName", "type": "str"}, - } - - def __init__(self, *, high_water_mark_column_name: str, **kwargs: Any) -> None: - """ - :keyword high_water_mark_column_name: The name of the high water mark column. Required. - :paramtype high_water_mark_column_name: str - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" - self.high_water_mark_column_name = high_water_mark_column_name - - -class HnswAlgorithmConfiguration(VectorSearchAlgorithmConfiguration): - """Contains configuration options specific to the HNSW approximate nearest neighbors algorithm - used during indexing and querying. The HNSW algorithm offers a tunable trade-off between search - speed and accuracy. - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular configuration. Required. - :vartype name: str - :ivar kind: The name of the kind of algorithm being configured for use with vector search. - Required. Known values are: "hnsw" and "exhaustiveKnn". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind - :ivar parameters: Contains the parameters specific to HNSW algorithm. - :vartype parameters: ~azure.search.documents.indexes.models.HnswParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "parameters": {"key": "hnswParameters", "type": "HnswParameters"}, - } - - def __init__(self, *, name: str, parameters: Optional["_models.HnswParameters"] = None, **kwargs: Any) -> None: - """ - :keyword name: The name to associate with this particular configuration. Required. - :paramtype name: str - :keyword parameters: Contains the parameters specific to HNSW algorithm. - :paramtype parameters: ~azure.search.documents.indexes.models.HnswParameters - """ - super().__init__(name=name, **kwargs) - self.kind: str = "hnsw" - self.parameters = parameters - - -class HnswParameters(_serialization.Model): - """Contains the parameters specific to the HNSW algorithm. - - :ivar m: The number of bi-directional links created for every new element during construction. - Increasing this parameter value may improve recall and reduce retrieval times for datasets with - high intrinsic dimensionality at the expense of increased memory consumption and longer - indexing time. - :vartype m: int - :ivar ef_construction: The size of the dynamic list containing the nearest neighbors, which is - used during index time. Increasing this parameter may improve index quality, at the expense of - increased indexing time. At a certain point, increasing this parameter leads to diminishing - returns. - :vartype ef_construction: int - :ivar ef_search: The size of the dynamic list containing the nearest neighbors, which is used - during search time. Increasing this parameter may improve search results, at the expense of - slower search. At a certain point, increasing this parameter leads to diminishing returns. - :vartype ef_search: int - :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", - "euclidean", "dotProduct", and "hamming". - :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - - _validation = { - "m": {"maximum": 10, "minimum": 4}, - "ef_construction": {"maximum": 1000, "minimum": 100}, - "ef_search": {"maximum": 1000, "minimum": 100}, - } - - _attribute_map = { - "m": {"key": "m", "type": "int"}, - "ef_construction": {"key": "efConstruction", "type": "int"}, - "ef_search": {"key": "efSearch", "type": "int"}, - "metric": {"key": "metric", "type": "str"}, - } - - def __init__( - self, - *, - m: int = 4, - ef_construction: int = 400, - ef_search: int = 500, - metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword m: The number of bi-directional links created for every new element during - construction. Increasing this parameter value may improve recall and reduce retrieval times for - datasets with high intrinsic dimensionality at the expense of increased memory consumption and - longer indexing time. - :paramtype m: int - :keyword ef_construction: The size of the dynamic list containing the nearest neighbors, which - is used during index time. Increasing this parameter may improve index quality, at the expense - of increased indexing time. At a certain point, increasing this parameter leads to diminishing - returns. - :paramtype ef_construction: int - :keyword ef_search: The size of the dynamic list containing the nearest neighbors, which is - used during search time. Increasing this parameter may improve search results, at the expense - of slower search. At a certain point, increasing this parameter leads to diminishing returns. - :paramtype ef_search: int - :keyword metric: The similarity metric to use for vector comparisons. Known values are: - "cosine", "euclidean", "dotProduct", and "hamming". - :paramtype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric - """ - super().__init__(**kwargs) - self.m = m - self.ef_construction = ef_construction - self.ef_search = ef_search - self.metric = metric - - -class ImageAnalysisSkill(SearchIndexerSkill): - """A skill that analyzes image files. It extracts a rich set of visual features based on the image - content. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "ar", "az", "bg", "bs", "ca", "cs", "cy", "da", "de", "el", "en", "es", "et", - "eu", "fi", "fr", "ga", "gl", "he", "hi", "hr", "hu", "id", "it", "ja", "kk", "ko", "lt", "lv", - "mk", "ms", "nb", "nl", "pl", "prs", "pt-BR", "pt", "pt-PT", "ro", "ru", "sk", "sl", "sr-Cyrl", - "sr-Latn", "sv", "th", "tr", "uk", "vi", "zh", "zh-Hans", and "zh-Hant". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.ImageAnalysisSkillLanguage - :ivar visual_features: A list of visual features. - :vartype visual_features: list[str or ~azure.search.documents.indexes.models.VisualFeature] - :ivar details: A string indicating which domain-specific details to return. - :vartype details: list[str or ~azure.search.documents.indexes.models.ImageDetail] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "visual_features": {"key": "visualFeatures", "type": "[str]"}, - "details": {"key": "details", "type": "[str]"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.ImageAnalysisSkillLanguage"]] = None, - visual_features: Optional[list[Union[str, "_models.VisualFeature"]]] = None, - details: Optional[list[Union[str, "_models.ImageDetail"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "ar", "az", "bg", "bs", "ca", "cs", "cy", "da", "de", "el", "en", - "es", "et", "eu", "fi", "fr", "ga", "gl", "he", "hi", "hr", "hu", "id", "it", "ja", "kk", "ko", - "lt", "lv", "mk", "ms", "nb", "nl", "pl", "prs", "pt-BR", "pt", "pt-PT", "ro", "ru", "sk", - "sl", "sr-Cyrl", "sr-Latn", "sv", "th", "tr", "uk", "vi", "zh", "zh-Hans", and "zh-Hant". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.ImageAnalysisSkillLanguage - :keyword visual_features: A list of visual features. - :paramtype visual_features: list[str or ~azure.search.documents.indexes.models.VisualFeature] - :keyword details: A string indicating which domain-specific details to return. - :paramtype details: list[str or ~azure.search.documents.indexes.models.ImageDetail] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Vision.ImageAnalysisSkill" - self.default_language_code = default_language_code - self.visual_features = visual_features - self.details = details - - -class IndexerCurrentState(_serialization.Model): - """Represents all of the state that defines and dictates the indexer's current execution. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", - "indexingResetDocs", and "indexingResync". - :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode - :ivar all_docs_initial_tracking_state: Change tracking state used when indexing starts on all - documents in the datasource. - :vartype all_docs_initial_tracking_state: str - :ivar all_docs_final_tracking_state: Change tracking state value when indexing finishes on all - documents in the datasource. - :vartype all_docs_final_tracking_state: str - :ivar reset_docs_initial_tracking_state: Change tracking state used when indexing starts on - select, reset documents in the datasource. - :vartype reset_docs_initial_tracking_state: str - :ivar reset_docs_final_tracking_state: Change tracking state value when indexing finishes on - select, reset documents in the datasource. - :vartype reset_docs_final_tracking_state: str - :ivar reset_document_keys: The list of document keys that have been reset. The document key is - the document's unique identifier for the data in the search index. The indexer will prioritize - selectively re-ingesting these keys. - :vartype reset_document_keys: list[str] - :ivar reset_datasource_document_ids: The list of datasource document ids that have been reset. - The datasource document id is the unique identifier for the data in the datasource. The indexer - will prioritize selectively re-ingesting these ids. - :vartype reset_datasource_document_ids: list[str] - :ivar resync_initial_tracking_state: Change tracking state used when indexing starts on - selective options from the datasource. - :vartype resync_initial_tracking_state: str - :ivar resync_final_tracking_state: Change tracking state value when indexing finishes on - selective options from the datasource. - :vartype resync_final_tracking_state: str - """ - - _validation = { - "mode": {"readonly": True}, - "all_docs_initial_tracking_state": {"readonly": True}, - "all_docs_final_tracking_state": {"readonly": True}, - "reset_docs_initial_tracking_state": {"readonly": True}, - "reset_docs_final_tracking_state": {"readonly": True}, - "reset_document_keys": {"readonly": True}, - "reset_datasource_document_ids": {"readonly": True}, - "resync_initial_tracking_state": {"readonly": True}, - "resync_final_tracking_state": {"readonly": True}, - } - - _attribute_map = { - "mode": {"key": "mode", "type": "str"}, - "all_docs_initial_tracking_state": {"key": "allDocsInitialTrackingState", "type": "str"}, - "all_docs_final_tracking_state": {"key": "allDocsFinalTrackingState", "type": "str"}, - "reset_docs_initial_tracking_state": {"key": "resetDocsInitialTrackingState", "type": "str"}, - "reset_docs_final_tracking_state": {"key": "resetDocsFinalTrackingState", "type": "str"}, - "reset_document_keys": {"key": "resetDocumentKeys", "type": "[str]"}, - "reset_datasource_document_ids": {"key": "resetDatasourceDocumentIds", "type": "[str]"}, - "resync_initial_tracking_state": {"key": "resyncInitialTrackingState", "type": "str"}, - "resync_final_tracking_state": {"key": "resyncFinalTrackingState", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.mode: Optional[Union[str, "_models.IndexingMode"]] = None - self.all_docs_initial_tracking_state: Optional[str] = None - self.all_docs_final_tracking_state: Optional[str] = None - self.reset_docs_initial_tracking_state: Optional[str] = None - self.reset_docs_final_tracking_state: Optional[str] = None - self.reset_document_keys: Optional[list[str]] = None - self.reset_datasource_document_ids: Optional[list[str]] = None - self.resync_initial_tracking_state: Optional[str] = None - self.resync_final_tracking_state: Optional[str] = None - - -class IndexerExecutionResult(_serialization.Model): - """Represents the result of an individual indexer execution. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar status: The outcome of this indexer execution. Required. Known values are: - "transientFailure", "success", "inProgress", and "reset". - :vartype status: str or ~azure.search.documents.indexes.models.IndexerExecutionStatus - :ivar status_detail: The outcome of this indexer execution. Known values are: "resetDocs" and - "resync". - :vartype status_detail: str or - ~azure.search.documents.indexes.models.IndexerExecutionStatusDetail - :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", - "indexingResetDocs", and "indexingResync". - :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode - :ivar error_message: The error message indicating the top-level error, if any. - :vartype error_message: str - :ivar start_time: The start time of this indexer execution. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of this indexer execution, if the execution has already completed. - :vartype end_time: ~datetime.datetime - :ivar errors: The item-level indexing errors. Required. - :vartype errors: list[~azure.search.documents.indexes.models.SearchIndexerError] - :ivar warnings: The item-level indexing warnings. Required. - :vartype warnings: list[~azure.search.documents.indexes.models.SearchIndexerWarning] - :ivar item_count: The number of items that were processed during this indexer execution. This - includes both successfully processed items and items where indexing was attempted but failed. - Required. - :vartype item_count: int - :ivar failed_item_count: The number of items that failed to be indexed during this indexer - execution. Required. - :vartype failed_item_count: int - :ivar initial_tracking_state: Change tracking state with which an indexer execution started. - :vartype initial_tracking_state: str - :ivar final_tracking_state: Change tracking state with which an indexer execution finished. - :vartype final_tracking_state: str - """ - - _validation = { - "status": {"required": True, "readonly": True}, - "status_detail": {"readonly": True}, - "mode": {"readonly": True}, - "error_message": {"readonly": True}, - "start_time": {"readonly": True}, - "end_time": {"readonly": True}, - "errors": {"required": True, "readonly": True}, - "warnings": {"required": True, "readonly": True}, - "item_count": {"required": True, "readonly": True}, - "failed_item_count": {"required": True, "readonly": True}, - "initial_tracking_state": {"readonly": True}, - "final_tracking_state": {"readonly": True}, - } - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - "status_detail": {"key": "statusDetail", "type": "str"}, - "mode": {"key": "mode", "type": "str"}, - "error_message": {"key": "errorMessage", "type": "str"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "errors": {"key": "errors", "type": "[SearchIndexerError]"}, - "warnings": {"key": "warnings", "type": "[SearchIndexerWarning]"}, - "item_count": {"key": "itemsProcessed", "type": "int"}, - "failed_item_count": {"key": "itemsFailed", "type": "int"}, - "initial_tracking_state": {"key": "initialTrackingState", "type": "str"}, - "final_tracking_state": {"key": "finalTrackingState", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.status: Optional[Union[str, "_models.IndexerExecutionStatus"]] = None - self.status_detail: Optional[Union[str, "_models.IndexerExecutionStatusDetail"]] = None - self.mode: Optional[Union[str, "_models.IndexingMode"]] = None - self.error_message: Optional[str] = None - self.start_time: Optional[datetime.datetime] = None - self.end_time: Optional[datetime.datetime] = None - self.errors: Optional[list["_models.SearchIndexerError"]] = None - self.warnings: Optional[list["_models.SearchIndexerWarning"]] = None - self.item_count: Optional[int] = None - self.failed_item_count: Optional[int] = None - self.initial_tracking_state: Optional[str] = None - self.final_tracking_state: Optional[str] = None - - -class IndexerResyncBody(_serialization.Model): - """IndexerResyncBody. - - :ivar options: Re-sync options that have been pre-defined from data source. - :vartype options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] - """ - - _attribute_map = { - "options": {"key": "options", "type": "[str]"}, - } - - def __init__( - self, *, options: Optional[list[Union[str, "_models.IndexerResyncOption"]]] = None, **kwargs: Any - ) -> None: - """ - :keyword options: Re-sync options that have been pre-defined from data source. - :paramtype options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] - """ - super().__init__(**kwargs) - self.options = options - - -class IndexingParameters(_serialization.Model): - """Represents parameters for indexer execution. - - :ivar batch_size: The number of items that are read from the data source and indexed as a - single batch in order to improve performance. The default depends on the data source type. - :vartype batch_size: int - :ivar max_failed_items: The maximum number of items that can fail indexing for indexer - execution to still be considered successful. -1 means no limit. Default is 0. - :vartype max_failed_items: int - :ivar max_failed_items_per_batch: The maximum number of items in a single batch that can fail - indexing for the batch to still be considered successful. -1 means no limit. Default is 0. - :vartype max_failed_items_per_batch: int - :ivar configuration: A dictionary of indexer-specific configuration properties. Each name is - the name of a specific property. Each value must be of a primitive type. - :vartype configuration: ~azure.search.documents.indexes.models.IndexingParametersConfiguration - """ - - _attribute_map = { - "batch_size": {"key": "batchSize", "type": "int"}, - "max_failed_items": {"key": "maxFailedItems", "type": "int"}, - "max_failed_items_per_batch": {"key": "maxFailedItemsPerBatch", "type": "int"}, - "configuration": {"key": "configuration", "type": "IndexingParametersConfiguration"}, - } - - def __init__( - self, - *, - batch_size: Optional[int] = None, - max_failed_items: int = 0, - max_failed_items_per_batch: int = 0, - configuration: Optional["_models.IndexingParametersConfiguration"] = None, - **kwargs: Any - ) -> None: - """ - :keyword batch_size: The number of items that are read from the data source and indexed as a - single batch in order to improve performance. The default depends on the data source type. - :paramtype batch_size: int - :keyword max_failed_items: The maximum number of items that can fail indexing for indexer - execution to still be considered successful. -1 means no limit. Default is 0. - :paramtype max_failed_items: int - :keyword max_failed_items_per_batch: The maximum number of items in a single batch that can - fail indexing for the batch to still be considered successful. -1 means no limit. Default is 0. - :paramtype max_failed_items_per_batch: int - :keyword configuration: A dictionary of indexer-specific configuration properties. Each name is - the name of a specific property. Each value must be of a primitive type. - :paramtype configuration: - ~azure.search.documents.indexes.models.IndexingParametersConfiguration - """ - super().__init__(**kwargs) - self.batch_size = batch_size - self.max_failed_items = max_failed_items - self.max_failed_items_per_batch = max_failed_items_per_batch - self.configuration = configuration - - -class IndexingParametersConfiguration(_serialization.Model): - """A dictionary of indexer-specific configuration properties. Each name is the name of a specific - property. Each value must be of a primitive type. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar parsing_mode: Represents the parsing mode for indexing from an Azure blob data source. - Known values are: "default", "text", "delimitedText", "json", "jsonArray", "jsonLines", and - "markdown". - :vartype parsing_mode: str or ~azure.search.documents.indexes.models.BlobIndexerParsingMode - :ivar excluded_file_name_extensions: Comma-delimited list of filename extensions to ignore when - processing from Azure blob storage. For example, you could exclude ".png, .mp4" to skip over - those files during indexing. - :vartype excluded_file_name_extensions: str - :ivar indexed_file_name_extensions: Comma-delimited list of filename extensions to select when - processing from Azure blob storage. For example, you could focus indexing on specific - application files ".docx, .pptx, .msg" to specifically include those file types. - :vartype indexed_file_name_extensions: str - :ivar fail_on_unsupported_content_type: For Azure blobs, set to false if you want to continue - indexing when an unsupported content type is encountered, and you don't know all the content - types (file extensions) in advance. - :vartype fail_on_unsupported_content_type: bool - :ivar fail_on_unprocessable_document: For Azure blobs, set to false if you want to continue - indexing if a document fails indexing. - :vartype fail_on_unprocessable_document: bool - :ivar index_storage_metadata_only_for_oversized_documents: For Azure blobs, set this property - to true to still index storage metadata for blob content that is too large to process. - Oversized blobs are treated as errors by default. For limits on blob size, see - https://learn.microsoft.com/azure/search/search-limits-quotas-capacity. - :vartype index_storage_metadata_only_for_oversized_documents: bool - :ivar delimited_text_headers: For CSV blobs, specifies a comma-delimited list of column - headers, useful for mapping source fields to destination fields in an index. - :vartype delimited_text_headers: str - :ivar delimited_text_delimiter: For CSV blobs, specifies the end-of-line single-character - delimiter for CSV files where each line starts a new document (for example, "|"). - :vartype delimited_text_delimiter: str - :ivar first_line_contains_headers: For CSV blobs, indicates that the first (non-blank) line of - each blob contains headers. - :vartype first_line_contains_headers: bool - :ivar markdown_parsing_submode: Specifies the submode that will determine whether a markdown - file will be parsed into exactly one search document or multiple search documents. Default is - ``oneToMany``. Known values are: "oneToMany" and "oneToOne". - :vartype markdown_parsing_submode: str or - ~azure.search.documents.indexes.models.MarkdownParsingSubmode - :ivar markdown_header_depth: Specifies the max header depth that will be considered while - grouping markdown content. Default is ``h6``. Known values are: "h1", "h2", "h3", "h4", "h5", - and "h6". - :vartype markdown_header_depth: str or - ~azure.search.documents.indexes.models.MarkdownHeaderDepth - :ivar document_root: For JSON arrays, given a structured or semi-structured document, you can - specify a path to the array using this property. - :vartype document_root: str - :ivar data_to_extract: Specifies the data to extract from Azure blob storage and tells the - indexer which data to extract from image content when "imageAction" is set to a value other - than "none". This applies to embedded image content in a .PDF or other application, or image - files such as .jpg and .png, in Azure blobs. Known values are: "storageMetadata", - "allMetadata", and "contentAndMetadata". - :vartype data_to_extract: str or - ~azure.search.documents.indexes.models.BlobIndexerDataToExtract - :ivar image_action: Determines how to process embedded images and image files in Azure blob - storage. Setting the "imageAction" configuration to any value other than "none" requires that - a skillset also be attached to that indexer. Known values are: "none", - "generateNormalizedImages", and "generateNormalizedImagePerPage". - :vartype image_action: str or ~azure.search.documents.indexes.models.BlobIndexerImageAction - :ivar allow_skillset_to_read_file_data: If true, will create a path //document//file_data that - is an object representing the original file data downloaded from your blob data source. This - allows you to pass the original file data to a custom skill for processing within the - enrichment pipeline, or to the Document Extraction skill. - :vartype allow_skillset_to_read_file_data: bool - :ivar pdf_text_rotation_algorithm: Determines algorithm for text extraction from PDF files in - Azure blob storage. Known values are: "none" and "detectAngles". - :vartype pdf_text_rotation_algorithm: str or - ~azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm - :ivar execution_environment: Specifies the environment in which the indexer should execute. - Known values are: "standard" and "private". - :vartype execution_environment: str or - ~azure.search.documents.indexes.models.IndexerExecutionEnvironment - :ivar query_timeout: Increases the timeout beyond the 5-minute default for Azure SQL database - data sources, specified in the format "hh:mm:ss". - :vartype query_timeout: str - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "parsing_mode": {"key": "parsingMode", "type": "str"}, - "excluded_file_name_extensions": {"key": "excludedFileNameExtensions", "type": "str"}, - "indexed_file_name_extensions": {"key": "indexedFileNameExtensions", "type": "str"}, - "fail_on_unsupported_content_type": {"key": "failOnUnsupportedContentType", "type": "bool"}, - "fail_on_unprocessable_document": {"key": "failOnUnprocessableDocument", "type": "bool"}, - "index_storage_metadata_only_for_oversized_documents": { - "key": "indexStorageMetadataOnlyForOversizedDocuments", - "type": "bool", - }, - "delimited_text_headers": {"key": "delimitedTextHeaders", "type": "str"}, - "delimited_text_delimiter": {"key": "delimitedTextDelimiter", "type": "str"}, - "first_line_contains_headers": {"key": "firstLineContainsHeaders", "type": "bool"}, - "markdown_parsing_submode": {"key": "markdownParsingSubmode", "type": "str"}, - "markdown_header_depth": {"key": "markdownHeaderDepth", "type": "str"}, - "document_root": {"key": "documentRoot", "type": "str"}, - "data_to_extract": {"key": "dataToExtract", "type": "str"}, - "image_action": {"key": "imageAction", "type": "str"}, - "allow_skillset_to_read_file_data": {"key": "allowSkillsetToReadFileData", "type": "bool"}, - "pdf_text_rotation_algorithm": {"key": "pdfTextRotationAlgorithm", "type": "str"}, - "execution_environment": {"key": "executionEnvironment", "type": "str"}, - "query_timeout": {"key": "queryTimeout", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - parsing_mode: Union[str, "_models.BlobIndexerParsingMode"] = "default", - excluded_file_name_extensions: str = "", - indexed_file_name_extensions: str = "", - fail_on_unsupported_content_type: bool = False, - fail_on_unprocessable_document: bool = False, - index_storage_metadata_only_for_oversized_documents: bool = False, - delimited_text_headers: Optional[str] = None, - delimited_text_delimiter: Optional[str] = None, - first_line_contains_headers: bool = True, - markdown_parsing_submode: Union[str, "_models.MarkdownParsingSubmode"] = "oneToMany", - markdown_header_depth: Union[str, "_models.MarkdownHeaderDepth"] = "h6", - document_root: Optional[str] = None, - data_to_extract: Union[str, "_models.BlobIndexerDataToExtract"] = "contentAndMetadata", - image_action: Union[str, "_models.BlobIndexerImageAction"] = "none", - allow_skillset_to_read_file_data: bool = False, - pdf_text_rotation_algorithm: Union[str, "_models.BlobIndexerPDFTextRotationAlgorithm"] = "none", - execution_environment: Union[str, "_models.IndexerExecutionEnvironment"] = "standard", - query_timeout: str = "00:05:00", - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword parsing_mode: Represents the parsing mode for indexing from an Azure blob data source. - Known values are: "default", "text", "delimitedText", "json", "jsonArray", "jsonLines", and - "markdown". - :paramtype parsing_mode: str or ~azure.search.documents.indexes.models.BlobIndexerParsingMode - :keyword excluded_file_name_extensions: Comma-delimited list of filename extensions to ignore - when processing from Azure blob storage. For example, you could exclude ".png, .mp4" to skip - over those files during indexing. - :paramtype excluded_file_name_extensions: str - :keyword indexed_file_name_extensions: Comma-delimited list of filename extensions to select - when processing from Azure blob storage. For example, you could focus indexing on specific - application files ".docx, .pptx, .msg" to specifically include those file types. - :paramtype indexed_file_name_extensions: str - :keyword fail_on_unsupported_content_type: For Azure blobs, set to false if you want to - continue indexing when an unsupported content type is encountered, and you don't know all the - content types (file extensions) in advance. - :paramtype fail_on_unsupported_content_type: bool - :keyword fail_on_unprocessable_document: For Azure blobs, set to false if you want to continue - indexing if a document fails indexing. - :paramtype fail_on_unprocessable_document: bool - :keyword index_storage_metadata_only_for_oversized_documents: For Azure blobs, set this - property to true to still index storage metadata for blob content that is too large to process. - Oversized blobs are treated as errors by default. For limits on blob size, see - https://learn.microsoft.com/azure/search/search-limits-quotas-capacity. - :paramtype index_storage_metadata_only_for_oversized_documents: bool - :keyword delimited_text_headers: For CSV blobs, specifies a comma-delimited list of column - headers, useful for mapping source fields to destination fields in an index. - :paramtype delimited_text_headers: str - :keyword delimited_text_delimiter: For CSV blobs, specifies the end-of-line single-character - delimiter for CSV files where each line starts a new document (for example, "|"). - :paramtype delimited_text_delimiter: str - :keyword first_line_contains_headers: For CSV blobs, indicates that the first (non-blank) line - of each blob contains headers. - :paramtype first_line_contains_headers: bool - :keyword markdown_parsing_submode: Specifies the submode that will determine whether a markdown - file will be parsed into exactly one search document or multiple search documents. Default is - ``oneToMany``. Known values are: "oneToMany" and "oneToOne". - :paramtype markdown_parsing_submode: str or - ~azure.search.documents.indexes.models.MarkdownParsingSubmode - :keyword markdown_header_depth: Specifies the max header depth that will be considered while - grouping markdown content. Default is ``h6``. Known values are: "h1", "h2", "h3", "h4", "h5", - and "h6". - :paramtype markdown_header_depth: str or - ~azure.search.documents.indexes.models.MarkdownHeaderDepth - :keyword document_root: For JSON arrays, given a structured or semi-structured document, you - can specify a path to the array using this property. - :paramtype document_root: str - :keyword data_to_extract: Specifies the data to extract from Azure blob storage and tells the - indexer which data to extract from image content when "imageAction" is set to a value other - than "none". This applies to embedded image content in a .PDF or other application, or image - files such as .jpg and .png, in Azure blobs. Known values are: "storageMetadata", - "allMetadata", and "contentAndMetadata". - :paramtype data_to_extract: str or - ~azure.search.documents.indexes.models.BlobIndexerDataToExtract - :keyword image_action: Determines how to process embedded images and image files in Azure blob - storage. Setting the "imageAction" configuration to any value other than "none" requires that - a skillset also be attached to that indexer. Known values are: "none", - "generateNormalizedImages", and "generateNormalizedImagePerPage". - :paramtype image_action: str or ~azure.search.documents.indexes.models.BlobIndexerImageAction - :keyword allow_skillset_to_read_file_data: If true, will create a path //document//file_data - that is an object representing the original file data downloaded from your blob data source. - This allows you to pass the original file data to a custom skill for processing within the - enrichment pipeline, or to the Document Extraction skill. - :paramtype allow_skillset_to_read_file_data: bool - :keyword pdf_text_rotation_algorithm: Determines algorithm for text extraction from PDF files - in Azure blob storage. Known values are: "none" and "detectAngles". - :paramtype pdf_text_rotation_algorithm: str or - ~azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm - :keyword execution_environment: Specifies the environment in which the indexer should execute. - Known values are: "standard" and "private". - :paramtype execution_environment: str or - ~azure.search.documents.indexes.models.IndexerExecutionEnvironment - :keyword query_timeout: Increases the timeout beyond the 5-minute default for Azure SQL - database data sources, specified in the format "hh:mm:ss". - :paramtype query_timeout: str - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.parsing_mode = parsing_mode - self.excluded_file_name_extensions = excluded_file_name_extensions - self.indexed_file_name_extensions = indexed_file_name_extensions - self.fail_on_unsupported_content_type = fail_on_unsupported_content_type - self.fail_on_unprocessable_document = fail_on_unprocessable_document - self.index_storage_metadata_only_for_oversized_documents = index_storage_metadata_only_for_oversized_documents - self.delimited_text_headers = delimited_text_headers - self.delimited_text_delimiter = delimited_text_delimiter - self.first_line_contains_headers = first_line_contains_headers - self.markdown_parsing_submode = markdown_parsing_submode - self.markdown_header_depth = markdown_header_depth - self.document_root = document_root - self.data_to_extract = data_to_extract - self.image_action = image_action - self.allow_skillset_to_read_file_data = allow_skillset_to_read_file_data - self.pdf_text_rotation_algorithm = pdf_text_rotation_algorithm - self.execution_environment = execution_environment - self.query_timeout = query_timeout - - -class IndexingSchedule(_serialization.Model): - """Represents a schedule for indexer execution. - - All required parameters must be populated in order to send to server. - - :ivar interval: The interval of time between indexer executions. Required. - :vartype interval: ~datetime.timedelta - :ivar start_time: The time when an indexer should start running. - :vartype start_time: ~datetime.datetime - """ - - _validation = { - "interval": {"required": True}, - } - - _attribute_map = { - "interval": {"key": "interval", "type": "duration"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - } - - def __init__( - self, *, interval: datetime.timedelta, start_time: Optional[datetime.datetime] = None, **kwargs: Any - ) -> None: - """ - :keyword interval: The interval of time between indexer executions. Required. - :paramtype interval: ~datetime.timedelta - :keyword start_time: The time when an indexer should start running. - :paramtype start_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.interval = interval - self.start_time = start_time - - -class IndexStatisticsSummary(_serialization.Model): - """Statistics for a given index. Statistics are collected periodically and are not guaranteed to - always be up-to-date. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the index. Required. - :vartype name: str - :ivar document_count: The number of documents in the index. Required. - :vartype document_count: int - :ivar storage_size: The amount of storage in bytes consumed by the index. Required. - :vartype storage_size: int - :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. - Required. - :vartype vector_index_size: int - """ - - _validation = { - "name": {"required": True}, - "document_count": {"required": True, "readonly": True}, - "storage_size": {"required": True, "readonly": True}, - "vector_index_size": {"required": True, "readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "document_count": {"key": "documentCount", "type": "int"}, - "storage_size": {"key": "storageSize", "type": "int"}, - "vector_index_size": {"key": "vectorIndexSize", "type": "int"}, - } - - def __init__(self, *, name: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the index. Required. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - self.document_count: Optional[int] = None - self.storage_size: Optional[int] = None - self.vector_index_size: Optional[int] = None - - -class InputFieldMappingEntry(_serialization.Model): - """Input field mapping for a skill. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the input. Required. - :vartype name: str - :ivar source: The source of the input. - :vartype source: str - :ivar source_context: The source context used for selecting recursive inputs. - :vartype source_context: str - :ivar inputs: The recursive inputs used when creating a complex type. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - name: str, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the input. Required. - :paramtype name: str - :keyword source: The source of the input. - :paramtype source: str - :keyword source_context: The source context used for selecting recursive inputs. - :paramtype source_context: str - :keyword inputs: The recursive inputs used when creating a complex type. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.name = name - self.source = source - self.source_context = source_context - self.inputs = inputs - - -class KeepTokenFilter(TokenFilter): - """A token filter that only keeps tokens with text contained in a specified list of words. This - token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar keep_words: The list of words to keep. Required. - :vartype keep_words: list[str] - :ivar lower_case_keep_words: A value indicating whether to lower case all words first. Default - is false. - :vartype lower_case_keep_words: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "keep_words": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "keep_words": {"key": "keepWords", "type": "[str]"}, - "lower_case_keep_words": {"key": "keepWordsCase", "type": "bool"}, - } - - def __init__(self, *, name: str, keep_words: list[str], lower_case_keep_words: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword keep_words: The list of words to keep. Required. - :paramtype keep_words: list[str] - :keyword lower_case_keep_words: A value indicating whether to lower case all words first. - Default is false. - :paramtype lower_case_keep_words: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeepTokenFilter" - self.keep_words = keep_words - self.lower_case_keep_words = lower_case_keep_words - - -class KeyPhraseExtractionSkill(SearchIndexerSkill): - """A skill that uses text analytics for key phrase extraction. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "nl", "en", "fi", "fr", "de", "it", "ja", "ko", "no", "pl", "pt-PT", - "pt-BR", "ru", "es", and "sv". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage - :ivar max_key_phrase_count: A number indicating how many key phrases to return. If absent, all - identified key phrases will be returned. - :vartype max_key_phrase_count: int - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "max_key_phrase_count": {"key": "maxKeyPhraseCount", "type": "int"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.KeyPhraseExtractionSkillLanguage"]] = None, - max_key_phrase_count: Optional[int] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "da", "nl", "en", "fi", "fr", "de", "it", "ja", "ko", "no", "pl", - "pt-PT", "pt-BR", "ru", "es", and "sv". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage - :keyword max_key_phrase_count: A number indicating how many key phrases to return. If absent, - all identified key phrases will be returned. - :paramtype max_key_phrase_count: int - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.KeyPhraseExtractionSkill" - self.default_language_code = default_language_code - self.max_key_phrase_count = max_key_phrase_count - self.model_version = model_version - - -class KeywordMarkerTokenFilter(TokenFilter): - """Marks terms as keywords. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar keywords: A list of words to mark as keywords. Required. - :vartype keywords: list[str] - :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted - to lower case first. Default is false. - :vartype ignore_case: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "keywords": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "keywords": {"key": "keywords", "type": "[str]"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - } - - def __init__(self, *, name: str, keywords: list[str], ignore_case: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword keywords: A list of words to mark as keywords. Required. - :paramtype keywords: list[str] - :keyword ignore_case: A value indicating whether to ignore case. If true, all words are - converted to lower case first. Default is false. - :paramtype ignore_case: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeywordMarkerTokenFilter" - self.keywords = keywords - self.ignore_case = ignore_case - - -class KeywordTokenizer(LexicalTokenizer): - """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar buffer_size: The read buffer size in bytes. Default is 256. - :vartype buffer_size: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "buffer_size": {"key": "bufferSize", "type": "int"}, - } - - def __init__(self, *, name: str, buffer_size: int = 256, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword buffer_size: The read buffer size in bytes. Default is 256. - :paramtype buffer_size: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeywordTokenizer" - self.buffer_size = buffer_size - - -class KeywordTokenizerV2(LexicalTokenizer): - """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 256. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 256, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 256. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.KeywordTokenizerV2" - self.max_token_length = max_token_length - - -class KnowledgeAgent(_serialization.Model): - """KnowledgeAgent. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge agent. Required. - :vartype name: str - :ivar models: Contains configuration options on how to connect to AI models. Required. - :vartype models: list[~azure.search.documents.indexes.models.KnowledgeAgentModel] - :ivar knowledge_sources: Required. - :vartype knowledge_sources: - list[~azure.search.documents.indexes.models.KnowledgeSourceReference] - :ivar output_configuration: - :vartype output_configuration: - ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfiguration - :ivar request_limits: Guardrails to limit how much resources are utilized for a single agent - retrieval request. - :vartype request_limits: ~azure.search.documents.indexes.models.KnowledgeAgentRequestLimits - :ivar retrieval_instructions: Instructions considered by the knowledge agent when developing - query plan. - :vartype retrieval_instructions: str - :ivar e_tag: The ETag of the agent. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar description: The description of the agent. - :vartype description: str - """ - - _validation = { - "name": {"required": True}, - "models": {"required": True}, - "knowledge_sources": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "models": {"key": "models", "type": "[KnowledgeAgentModel]"}, - "knowledge_sources": {"key": "knowledgeSources", "type": "[KnowledgeSourceReference]"}, - "output_configuration": {"key": "outputConfiguration", "type": "KnowledgeAgentOutputConfiguration"}, - "request_limits": {"key": "requestLimits", "type": "KnowledgeAgentRequestLimits"}, - "retrieval_instructions": {"key": "retrievalInstructions", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - models: list["_models.KnowledgeAgentModel"], - knowledge_sources: list["_models.KnowledgeSourceReference"], - output_configuration: Optional["_models.KnowledgeAgentOutputConfiguration"] = None, - request_limits: Optional["_models.KnowledgeAgentRequestLimits"] = None, - retrieval_instructions: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge agent. Required. - :paramtype name: str - :keyword models: Contains configuration options on how to connect to AI models. Required. - :paramtype models: list[~azure.search.documents.indexes.models.KnowledgeAgentModel] - :keyword knowledge_sources: Required. - :paramtype knowledge_sources: - list[~azure.search.documents.indexes.models.KnowledgeSourceReference] - :keyword output_configuration: - :paramtype output_configuration: - ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfiguration - :keyword request_limits: Guardrails to limit how much resources are utilized for a single agent - retrieval request. - :paramtype request_limits: ~azure.search.documents.indexes.models.KnowledgeAgentRequestLimits - :keyword retrieval_instructions: Instructions considered by the knowledge agent when developing - query plan. - :paramtype retrieval_instructions: str - :keyword e_tag: The ETag of the agent. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword description: The description of the agent. - :paramtype description: str - """ - super().__init__(**kwargs) - self.name = name - self.models = models - self.knowledge_sources = knowledge_sources - self.output_configuration = output_configuration - self.request_limits = request_limits - self.retrieval_instructions = retrieval_instructions - self.e_tag = e_tag - self.encryption_key = encryption_key - self.description = description - - -class KnowledgeAgentModel(_serialization.Model): - """Specifies the connection parameters for the model to use for query planning. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeAgentAzureOpenAIModel - - All required parameters must be populated in order to send to server. - - :ivar kind: The type of AI model. Required. "azureOpenAI" - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeAgentModelKind - """ - - _validation = { - "kind": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - } - - _subtype_map = {"kind": {"azureOpenAI": "KnowledgeAgentAzureOpenAIModel"}} - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class KnowledgeAgentAzureOpenAIModel(KnowledgeAgentModel): - """Specifies the Azure OpenAI resource used to do query planning. - - All required parameters must be populated in order to send to server. - - :ivar kind: The type of AI model. Required. "azureOpenAI" - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeAgentModelKind - :ivar azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI model - endpoint. Required. - :vartype azure_open_ai_parameters: - ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - - _validation = { - "kind": {"required": True}, - "azure_open_ai_parameters": {"required": True}, - } - - _attribute_map = { - "kind": {"key": "kind", "type": "str"}, - "azure_open_ai_parameters": {"key": "azureOpenAIParameters", "type": "AzureOpenAIVectorizerParameters"}, - } - - def __init__(self, *, azure_open_ai_parameters: "_models.AzureOpenAIVectorizerParameters", **kwargs: Any) -> None: - """ - :keyword azure_open_ai_parameters: Contains the parameters specific to Azure OpenAI model - endpoint. Required. - :paramtype azure_open_ai_parameters: - ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters - """ - super().__init__(**kwargs) - self.kind: str = "azureOpenAI" - self.azure_open_ai_parameters = azure_open_ai_parameters - - -class KnowledgeAgentOutputConfiguration(_serialization.Model): - """KnowledgeAgentOutputConfiguration. - - :ivar modality: The output configuration for the agent. Known values are: "answerSynthesis" and - "extractiveData". - :vartype modality: str or - ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfigurationModality - :ivar answer_instructions: Instructions considered by the knowledge agent when generating - answers. - :vartype answer_instructions: str - :ivar attempt_fast_path: Indicates whether the agent should attempt to issue the most recent - chat message as a direct query to the knowledge sources, bypassing the model calls. - :vartype attempt_fast_path: bool - :ivar include_activity: Indicates retrieval results should include activity information. - :vartype include_activity: bool - """ - - _attribute_map = { - "modality": {"key": "modality", "type": "str"}, - "answer_instructions": {"key": "answerInstructions", "type": "str"}, - "attempt_fast_path": {"key": "attemptFastPath", "type": "bool"}, - "include_activity": {"key": "includeActivity", "type": "bool"}, - } - - def __init__( - self, - *, - modality: Optional[Union[str, "_models.KnowledgeAgentOutputConfigurationModality"]] = None, - answer_instructions: Optional[str] = None, - attempt_fast_path: Optional[bool] = None, - include_activity: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword modality: The output configuration for the agent. Known values are: "answerSynthesis" - and "extractiveData". - :paramtype modality: str or - ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfigurationModality - :keyword answer_instructions: Instructions considered by the knowledge agent when generating - answers. - :paramtype answer_instructions: str - :keyword attempt_fast_path: Indicates whether the agent should attempt to issue the most recent - chat message as a direct query to the knowledge sources, bypassing the model calls. - :paramtype attempt_fast_path: bool - :keyword include_activity: Indicates retrieval results should include activity information. - :paramtype include_activity: bool - """ - super().__init__(**kwargs) - self.modality = modality - self.answer_instructions = answer_instructions - self.attempt_fast_path = attempt_fast_path - self.include_activity = include_activity - - -class KnowledgeAgentRequestLimits(_serialization.Model): - """Guardrails to limit how much resources are utilized for a single agent retrieval request. - - :ivar max_runtime_in_seconds: The maximum runtime in seconds. - :vartype max_runtime_in_seconds: int - :ivar max_output_size: Limits the maximum size of the content in the output. - :vartype max_output_size: int - """ - - _attribute_map = { - "max_runtime_in_seconds": {"key": "maxRuntimeInSeconds", "type": "int"}, - "max_output_size": {"key": "maxOutputSize", "type": "int"}, - } - - def __init__( - self, *, max_runtime_in_seconds: Optional[int] = None, max_output_size: Optional[int] = None, **kwargs: Any - ) -> None: - """ - :keyword max_runtime_in_seconds: The maximum runtime in seconds. - :paramtype max_runtime_in_seconds: int - :keyword max_output_size: Limits the maximum size of the content in the output. - :paramtype max_output_size: int - """ - super().__init__(**kwargs) - self.max_runtime_in_seconds = max_runtime_in_seconds - self.max_output_size = max_output_size - - -class KnowledgeSourceReference(_serialization.Model): - """KnowledgeSourceReference. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar max_sub_queries: The maximum number of queries that can be issued at a time when - retrieving data from this source. - :vartype max_sub_queries: int - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "include_references": {"key": "includeReferences", "type": "bool"}, - "include_reference_source_data": {"key": "includeReferenceSourceData", "type": "bool"}, - "always_query_source": {"key": "alwaysQuerySource", "type": "bool"}, - "max_sub_queries": {"key": "maxSubQueries", "type": "int"}, - "reranker_threshold": {"key": "rerankerThreshold", "type": "float"}, - } - - def __init__( - self, - *, - name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - max_sub_queries: Optional[int] = None, - reranker_threshold: Optional[float] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword include_references: Indicates whether references should be included for data retrieved - from this source. - :paramtype include_references: bool - :keyword include_reference_source_data: Indicates whether references should include the - structured data obtained during retrieval in their payload. - :paramtype include_reference_source_data: bool - :keyword always_query_source: Indicates that this knowledge source should bypass source - selection and always be queried at retrieval time. - :paramtype always_query_source: bool - :keyword max_sub_queries: The maximum number of queries that can be issued at a time when - retrieving data from this source. - :paramtype max_sub_queries: int - :keyword reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :paramtype reranker_threshold: float - """ - super().__init__(**kwargs) - self.name = name - self.include_references = include_references - self.include_reference_source_data = include_reference_source_data - self.always_query_source = always_query_source - self.max_sub_queries = max_sub_queries - self.reranker_threshold = reranker_threshold - - -class LanguageDetectionSkill(SearchIndexerSkill): - """A skill that detects the language of input text and reports a single language code for every - document submitted on the request. The language code is paired with a score indicating the - confidence of the analysis. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_country_hint: A country code to use as a hint to the language detection model if - it cannot disambiguate the language. - :vartype default_country_hint: str - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_country_hint": {"key": "defaultCountryHint", "type": "str"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_country_hint: Optional[str] = None, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_country_hint: A country code to use as a hint to the language detection model - if it cannot disambiguate the language. - :paramtype default_country_hint: str - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.LanguageDetectionSkill" - self.default_country_hint = default_country_hint - self.model_version = model_version - - -class LengthTokenFilter(TokenFilter): - """Removes words that are too long or too short. This token filter is implemented using Apache - Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_length: The minimum length in characters. Default is 0. Maximum is 300. Must be less - than the value of max. - :vartype min_length: int - :ivar max_length: The maximum length in characters. Default and maximum is 300. - :vartype max_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_length": {"maximum": 300}, - "max_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_length": {"key": "min", "type": "int"}, - "max_length": {"key": "max", "type": "int"}, - } - - def __init__(self, *, name: str, min_length: int = 0, max_length: int = 300, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_length: The minimum length in characters. Default is 0. Maximum is 300. Must be - less than the value of max. - :paramtype min_length: int - :keyword max_length: The maximum length in characters. Default and maximum is 300. - :paramtype max_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.LengthTokenFilter" - self.min_length = min_length - self.max_length = max_length - - -class LimitTokenFilter(TokenFilter): - """Limits the number of tokens while indexing. This token filter is implemented using Apache - Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_count: The maximum number of tokens to produce. Default is 1. - :vartype max_token_count: int - :ivar consume_all_tokens: A value indicating whether all tokens from the input must be consumed - even if maxTokenCount is reached. Default is false. - :vartype consume_all_tokens: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_count": {"key": "maxTokenCount", "type": "int"}, - "consume_all_tokens": {"key": "consumeAllTokens", "type": "bool"}, - } - - def __init__(self, *, name: str, max_token_count: int = 1, consume_all_tokens: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword max_token_count: The maximum number of tokens to produce. Default is 1. - :paramtype max_token_count: int - :keyword consume_all_tokens: A value indicating whether all tokens from the input must be - consumed even if maxTokenCount is reached. Default is false. - :paramtype consume_all_tokens: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.LimitTokenFilter" - self.max_token_count = max_token_count - self.consume_all_tokens = consume_all_tokens - - -class ListAliasesResult(_serialization.Model): - """Response from a List Aliases request. If successful, it includes the associated index mappings - for all aliases. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar aliases: The aliases in the Search service. Required. - :vartype aliases: list[~azure.search.documents.indexes.models.SearchAlias] - """ - - _validation = { - "aliases": {"required": True, "readonly": True}, - } - - _attribute_map = { - "aliases": {"key": "value", "type": "[SearchAlias]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.aliases: Optional[list["_models.SearchAlias"]] = None - - -class ListDataSourcesResult(_serialization.Model): - """Response from a List Datasources request. If successful, it includes the full definitions of - all datasources. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar data_sources: The datasources in the Search service. Required. - :vartype data_sources: list[~azure.search.documents.indexes.models.SearchIndexerDataSource] - """ - - _validation = { - "data_sources": {"required": True, "readonly": True}, - } - - _attribute_map = { - "data_sources": {"key": "value", "type": "[SearchIndexerDataSource]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.data_sources: Optional[list["_models.SearchIndexerDataSource"]] = None - - -class ListIndexersResult(_serialization.Model): - """Response from a List Indexers request. If successful, it includes the full definitions of all - indexers. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar indexers: The indexers in the Search service. Required. - :vartype indexers: list[~azure.search.documents.indexes.models.SearchIndexer] - """ - - _validation = { - "indexers": {"required": True, "readonly": True}, - } - - _attribute_map = { - "indexers": {"key": "value", "type": "[SearchIndexer]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.indexers: Optional[list["_models.SearchIndexer"]] = None - - -class ListIndexesResult(_serialization.Model): - """Response from a List Indexes request. If successful, it includes the full definitions of all - indexes. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar indexes: The indexes in the Search service. Required. - :vartype indexes: list[~azure.search.documents.indexes.models.SearchIndex] - """ - - _validation = { - "indexes": {"required": True, "readonly": True}, - } - - _attribute_map = { - "indexes": {"key": "value", "type": "[SearchIndex]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.indexes: Optional[list["_models.SearchIndex"]] = None - - -class ListIndexStatsSummary(_serialization.Model): - """Response from a request to retrieve stats summary of all indexes. If successful, it includes - the stats of each index in the service. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar indexes_statistics: The Statistics summary of all indexes in the Search service. - Required. - :vartype indexes_statistics: - list[~azure.search.documents.indexes.models.IndexStatisticsSummary] - """ - - _validation = { - "indexes_statistics": {"required": True, "readonly": True}, - } - - _attribute_map = { - "indexes_statistics": {"key": "value", "type": "[IndexStatisticsSummary]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.indexes_statistics: Optional[list["_models.IndexStatisticsSummary"]] = None - - -class ListKnowledgeAgentsResult(_serialization.Model): - """ListKnowledgeAgentsResult. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_agents: Required. - :vartype knowledge_agents: list[~azure.search.documents.indexes.models.KnowledgeAgent] - """ - - _validation = { - "knowledge_agents": {"required": True}, - } - - _attribute_map = { - "knowledge_agents": {"key": "value", "type": "[KnowledgeAgent]"}, - } - - def __init__(self, *, knowledge_agents: list["_models.KnowledgeAgent"], **kwargs: Any) -> None: - """ - :keyword knowledge_agents: Required. - :paramtype knowledge_agents: list[~azure.search.documents.indexes.models.KnowledgeAgent] - """ - super().__init__(**kwargs) - self.knowledge_agents = knowledge_agents - - -class ListKnowledgeSourcesResult(_serialization.Model): - """ListKnowledgeSourcesResult. - - All required parameters must be populated in order to send to server. - - :ivar knowledge_sources: Required. - :vartype knowledge_sources: list[~azure.search.documents.indexes.models.KnowledgeSource] - """ - - _validation = { - "knowledge_sources": {"required": True}, - } - - _attribute_map = { - "knowledge_sources": {"key": "value", "type": "[KnowledgeSource]"}, - } - - def __init__(self, *, knowledge_sources: list["_models.KnowledgeSource"], **kwargs: Any) -> None: - """ - :keyword knowledge_sources: Required. - :paramtype knowledge_sources: list[~azure.search.documents.indexes.models.KnowledgeSource] - """ - super().__init__(**kwargs) - self.knowledge_sources = knowledge_sources - - -class ListSkillsetsResult(_serialization.Model): - """Response from a list skillset request. If successful, it includes the full definitions of all - skillsets. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar skillsets: The skillsets defined in the Search service. Required. - :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - """ - - _validation = { - "skillsets": {"required": True, "readonly": True}, - } - - _attribute_map = { - "skillsets": {"key": "value", "type": "[SearchIndexerSkillset]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.skillsets: Optional[list["_models.SearchIndexerSkillset"]] = None - - -class ListSynonymMapsResult(_serialization.Model): - """Response from a List SynonymMaps request. If successful, it includes the full definitions of - all synonym maps. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar synonym_maps: The synonym maps in the Search service. Required. - :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] - """ - - _validation = { - "synonym_maps": {"required": True, "readonly": True}, - } - - _attribute_map = { - "synonym_maps": {"key": "value", "type": "[SynonymMap]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.synonym_maps: Optional[list["_models.SynonymMap"]] = None - - -class LuceneStandardAnalyzer(LexicalAnalyzer): - """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop - filter. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__( - self, *, name: str, max_token_length: int = 255, stopwords: Optional[list[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - :keyword stopwords: A list of stopwords. - :paramtype stopwords: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StandardAnalyzer" - self.max_token_length = max_token_length - self.stopwords = stopwords - - -class LuceneStandardTokenizer(LexicalTokenizer): - """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StandardTokenizer" - self.max_token_length = max_token_length - - -class LuceneStandardTokenizerV2(LexicalTokenizer): - """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StandardTokenizerV2" - self.max_token_length = max_token_length - - -class MagnitudeScoringFunction(ScoringFunction): - """Defines a function that boosts scores based on the magnitude of a numeric field. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the magnitude scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.MagnitudeScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "magnitude", "type": "MagnitudeScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.MagnitudeScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the magnitude scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.MagnitudeScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "magnitude" - self.parameters = parameters - - -class MagnitudeScoringParameters(_serialization.Model): - """Provides parameter values to a magnitude scoring function. - - All required parameters must be populated in order to send to server. - - :ivar boosting_range_start: The field value at which boosting starts. Required. - :vartype boosting_range_start: float - :ivar boosting_range_end: The field value at which boosting ends. Required. - :vartype boosting_range_end: float - :ivar should_boost_beyond_range_by_constant: A value indicating whether to apply a constant - boost for field values beyond the range end value; default is false. - :vartype should_boost_beyond_range_by_constant: bool - """ - - _validation = { - "boosting_range_start": {"required": True}, - "boosting_range_end": {"required": True}, - } - - _attribute_map = { - "boosting_range_start": {"key": "boostingRangeStart", "type": "float"}, - "boosting_range_end": {"key": "boostingRangeEnd", "type": "float"}, - "should_boost_beyond_range_by_constant": {"key": "constantBoostBeyondRange", "type": "bool"}, - } - - def __init__( - self, - *, - boosting_range_start: float, - boosting_range_end: float, - should_boost_beyond_range_by_constant: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword boosting_range_start: The field value at which boosting starts. Required. - :paramtype boosting_range_start: float - :keyword boosting_range_end: The field value at which boosting ends. Required. - :paramtype boosting_range_end: float - :keyword should_boost_beyond_range_by_constant: A value indicating whether to apply a constant - boost for field values beyond the range end value; default is false. - :paramtype should_boost_beyond_range_by_constant: bool - """ - super().__init__(**kwargs) - self.boosting_range_start = boosting_range_start - self.boosting_range_end = boosting_range_end - self.should_boost_beyond_range_by_constant = should_boost_beyond_range_by_constant - - -class MappingCharFilter(CharFilter): - """A character filter that applies mappings defined with the mappings option. Matching is greedy - (longest pattern matching at a given point wins). Replacement is allowed to be the empty - string. This character filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of char filter. Required. - :vartype odata_type: str - :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar mappings: A list of mappings of the following format: "a=>b" (all occurrences of the - character "a" will be replaced with character "b"). Required. - :vartype mappings: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "mappings": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "mappings": {"key": "mappings", "type": "[str]"}, - } - - def __init__(self, *, name: str, mappings: list[str], **kwargs: Any) -> None: - """ - :keyword name: The name of the char filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword mappings: A list of mappings of the following format: "a=>b" (all occurrences of the - character "a" will be replaced with character "b"). Required. - :paramtype mappings: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.MappingCharFilter" - self.mappings = mappings - - -class MergeSkill(SearchIndexerSkill): - """A skill for merging two or more strings into a single unified string, with an optional - user-defined delimiter separating each component part. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar insert_pre_tag: The tag indicates the start of the merged text. By default, the tag is an - empty space. - :vartype insert_pre_tag: str - :ivar insert_post_tag: The tag indicates the end of the merged text. By default, the tag is an - empty space. - :vartype insert_post_tag: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "insert_pre_tag": {"key": "insertPreTag", "type": "str"}, - "insert_post_tag": {"key": "insertPostTag", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - insert_pre_tag: str = " ", - insert_post_tag: str = " ", - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword insert_pre_tag: The tag indicates the start of the merged text. By default, the tag is - an empty space. - :paramtype insert_pre_tag: str - :keyword insert_post_tag: The tag indicates the end of the merged text. By default, the tag is - an empty space. - :paramtype insert_post_tag: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.MergeSkill" - self.insert_pre_tag = insert_pre_tag - self.insert_post_tag = insert_post_tag - - -class MicrosoftLanguageStemmingTokenizer(LexicalTokenizer): - """Divides text using language-specific rules and reduces words to their base forms. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :vartype max_token_length: int - :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as - the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :vartype is_search_tokenizer: bool - :ivar language: The language to use. The default is English. Known values are: "arabic", - "bangla", "bulgarian", "catalan", "croatian", "czech", "danish", "dutch", "english", - "estonian", "finnish", "french", "german", "greek", "gujarati", "hebrew", "hindi", "hungarian", - "icelandic", "indonesian", "italian", "kannada", "latvian", "lithuanian", "malay", "malayalam", - "marathi", "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", - "romanian", "russian", "serbianCyrillic", "serbianLatin", "slovak", "slovenian", "spanish", - "swedish", "tamil", "telugu", "turkish", "ukrainian", and "urdu". - :vartype language: str or - ~azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "is_search_tokenizer": {"key": "isSearchTokenizer", "type": "bool"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - max_token_length: int = 255, - is_search_tokenizer: bool = False, - language: Optional[Union[str, "_models.MicrosoftStemmingTokenizerLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :paramtype max_token_length: int - :keyword is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used - as the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :paramtype is_search_tokenizer: bool - :keyword language: The language to use. The default is English. Known values are: "arabic", - "bangla", "bulgarian", "catalan", "croatian", "czech", "danish", "dutch", "english", - "estonian", "finnish", "french", "german", "greek", "gujarati", "hebrew", "hindi", "hungarian", - "icelandic", "indonesian", "italian", "kannada", "latvian", "lithuanian", "malay", "malayalam", - "marathi", "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", - "romanian", "russian", "serbianCyrillic", "serbianLatin", "slovak", "slovenian", "spanish", - "swedish", "tamil", "telugu", "turkish", "ukrainian", and "urdu". - :paramtype language: str or - ~azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer" - self.max_token_length = max_token_length - self.is_search_tokenizer = is_search_tokenizer - self.language = language - - -class MicrosoftLanguageTokenizer(LexicalTokenizer): - """Divides text using language-specific rules. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :vartype max_token_length: int - :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as - the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :vartype is_search_tokenizer: bool - :ivar language: The language to use. The default is English. Known values are: "bangla", - "bulgarian", "catalan", "chineseSimplified", "chineseTraditional", "croatian", "czech", - "danish", "dutch", "english", "french", "german", "greek", "gujarati", "hindi", "icelandic", - "indonesian", "italian", "japanese", "kannada", "korean", "malay", "malayalam", "marathi", - "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", "romanian", - "russian", "serbianCyrillic", "serbianLatin", "slovenian", "spanish", "swedish", "tamil", - "telugu", "thai", "ukrainian", "urdu", and "vietnamese". - :vartype language: str or ~azure.search.documents.indexes.models.MicrosoftTokenizerLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "is_search_tokenizer": {"key": "isSearchTokenizer", "type": "bool"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - max_token_length: int = 255, - is_search_tokenizer: bool = False, - language: Optional[Union[str, "_models.MicrosoftTokenizerLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Tokens longer than the maximum length are - split. Maximum token length that can be used is 300 characters. Tokens longer than 300 - characters are first split into tokens of length 300 and then each of those tokens is split - based on the max token length set. Default is 255. - :paramtype max_token_length: int - :keyword is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used - as the search tokenizer, set to false if used as the indexing tokenizer. Default is false. - :paramtype is_search_tokenizer: bool - :keyword language: The language to use. The default is English. Known values are: "bangla", - "bulgarian", "catalan", "chineseSimplified", "chineseTraditional", "croatian", "czech", - "danish", "dutch", "english", "french", "german", "greek", "gujarati", "hindi", "icelandic", - "indonesian", "italian", "japanese", "kannada", "korean", "malay", "malayalam", "marathi", - "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", "romanian", - "russian", "serbianCyrillic", "serbianLatin", "slovenian", "spanish", "swedish", "tamil", - "telugu", "thai", "ukrainian", "urdu", and "vietnamese". - :paramtype language: str or ~azure.search.documents.indexes.models.MicrosoftTokenizerLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer" - self.max_token_length = max_token_length - self.is_search_tokenizer = is_search_tokenizer - self.language = language - - -class NativeBlobSoftDeleteDeletionDetectionPolicy(DataDeletionDetectionPolicy): # pylint: disable=name-too-long - """Defines a data deletion detection policy utilizing Azure Blob Storage's native soft delete - feature for deletion detection. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. - Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" - - -class NGramTokenFilter(TokenFilter): - """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. - :vartype max_gram: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - } - - def __init__(self, *, name: str, min_gram: int = 1, max_gram: int = 2, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Must be less than the value of - maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. - :paramtype max_gram: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NGramTokenFilter" - self.min_gram = min_gram - self.max_gram = max_gram - - -class NGramTokenFilterV2(TokenFilter): - """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - } - - def __init__(self, *, name: str, min_gram: int = 1, max_gram: int = 2, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NGramTokenFilterV2" - self.min_gram = min_gram - self.max_gram = max_gram - - -class NGramTokenizer(LexicalTokenizer): - """Tokenizes the input into n-grams of the given size(s). This tokenizer is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. - :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :vartype max_gram: int - :ivar token_chars: Character classes to keep in the tokens. - :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "min_gram": {"maximum": 300}, - "max_gram": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "min_gram": {"key": "minGram", "type": "int"}, - "max_gram": {"key": "maxGram", "type": "int"}, - "token_chars": {"key": "tokenChars", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - min_gram: int = 1, - max_gram: int = 2, - token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than - the value of maxGram. - :paramtype min_gram: int - :keyword max_gram: The maximum n-gram length. Default is 2. Maximum is 300. - :paramtype max_gram: int - :keyword token_chars: Character classes to keep in the tokens. - :paramtype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.NGramTokenizer" - self.min_gram = min_gram - self.max_gram = max_gram - self.token_chars = token_chars - - -class OcrSkill(SearchIndexerSkill): - """A skill that extracts text from image files. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "af", "sq", "anp", "ar", "ast", "awa", "az", "bfy", "eu", "be", "be-cyrl", - "be-latn", "bho", "bi", "brx", "bs", "bra", "br", "bg", "bns", "bua", "ca", "ceb", "rab", "ch", - "hne", "zh-Hans", "zh-Hant", "kw", "co", "crh", "hr", "cs", "da", "prs", "dhi", "doi", "nl", - "en", "myv", "et", "fo", "fj", "fil", "fi", "fr", "fur", "gag", "gl", "de", "gil", "gon", "el", - "kl", "gvr", "ht", "hlb", "hni", "bgc", "haw", "hi", "mww", "hoc", "hu", "is", "smn", "id", - "ia", "iu", "ga", "it", "ja", "Jns", "jv", "kea", "kac", "xnr", "krc", "kaa-cyrl", "kaa", - "csb", "kk-cyrl", "kk-latn", "klr", "kha", "quc", "ko", "kfq", "kpy", "kos", "kum", "ku-arab", - "ku-latn", "kru", "ky", "lkt", "la", "lt", "dsb", "smj", "lb", "bfz", "ms", "mt", "kmj", "gv", - "mi", "mr", "mn", "cnr-cyrl", "cnr-latn", "nap", "ne", "niu", "nog", "sme", "nb", "no", "oc", - "os", "ps", "fa", "pl", "pt", "pa", "ksh", "ro", "rm", "ru", "sck", "sm", "sa", "sat", "sco", - "gd", "sr", "sr-Cyrl", "sr-Latn", "xsr", "srx", "sms", "sk", "sl", "so", "sma", "es", "sw", - "sv", "tg", "tt", "tet", "thf", "to", "tr", "tk", "tyv", "hsb", "ur", "ug", "uz-arab", - "uz-cyrl", "uz", "vo", "wae", "cy", "fy", "yua", "za", "zu", "unk", and "is". - :vartype default_language_code: str or ~azure.search.documents.indexes.models.OcrSkillLanguage - :ivar should_detect_orientation: A value indicating to turn orientation detection on or not. - Default is false. - :vartype should_detect_orientation: bool - :ivar line_ending: Defines the sequence of characters to use between the lines of text - recognized by the OCR skill. The default value is "space". Known values are: "space", - "carriageReturn", "lineFeed", and "carriageReturnLineFeed". - :vartype line_ending: str or ~azure.search.documents.indexes.models.OcrLineEnding - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "should_detect_orientation": {"key": "detectOrientation", "type": "bool"}, - "line_ending": {"key": "lineEnding", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.OcrSkillLanguage"]] = None, - should_detect_orientation: bool = False, - line_ending: Optional[Union[str, "_models.OcrLineEnding"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "af", "sq", "anp", "ar", "ast", "awa", "az", "bfy", "eu", "be", - "be-cyrl", "be-latn", "bho", "bi", "brx", "bs", "bra", "br", "bg", "bns", "bua", "ca", "ceb", - "rab", "ch", "hne", "zh-Hans", "zh-Hant", "kw", "co", "crh", "hr", "cs", "da", "prs", "dhi", - "doi", "nl", "en", "myv", "et", "fo", "fj", "fil", "fi", "fr", "fur", "gag", "gl", "de", "gil", - "gon", "el", "kl", "gvr", "ht", "hlb", "hni", "bgc", "haw", "hi", "mww", "hoc", "hu", "is", - "smn", "id", "ia", "iu", "ga", "it", "ja", "Jns", "jv", "kea", "kac", "xnr", "krc", "kaa-cyrl", - "kaa", "csb", "kk-cyrl", "kk-latn", "klr", "kha", "quc", "ko", "kfq", "kpy", "kos", "kum", - "ku-arab", "ku-latn", "kru", "ky", "lkt", "la", "lt", "dsb", "smj", "lb", "bfz", "ms", "mt", - "kmj", "gv", "mi", "mr", "mn", "cnr-cyrl", "cnr-latn", "nap", "ne", "niu", "nog", "sme", "nb", - "no", "oc", "os", "ps", "fa", "pl", "pt", "pa", "ksh", "ro", "rm", "ru", "sck", "sm", "sa", - "sat", "sco", "gd", "sr", "sr-Cyrl", "sr-Latn", "xsr", "srx", "sms", "sk", "sl", "so", "sma", - "es", "sw", "sv", "tg", "tt", "tet", "thf", "to", "tr", "tk", "tyv", "hsb", "ur", "ug", - "uz-arab", "uz-cyrl", "uz", "vo", "wae", "cy", "fy", "yua", "za", "zu", "unk", and "is". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.OcrSkillLanguage - :keyword should_detect_orientation: A value indicating to turn orientation detection on or not. - Default is false. - :paramtype should_detect_orientation: bool - :keyword line_ending: Defines the sequence of characters to use between the lines of text - recognized by the OCR skill. The default value is "space". Known values are: "space", - "carriageReturn", "lineFeed", and "carriageReturnLineFeed". - :paramtype line_ending: str or ~azure.search.documents.indexes.models.OcrLineEnding - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Vision.OcrSkill" - self.default_language_code = default_language_code - self.should_detect_orientation = should_detect_orientation - self.line_ending = line_ending - - -class OutputFieldMappingEntry(_serialization.Model): - """Output field mapping for a skill. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the output defined by the skill. Required. - :vartype name: str - :ivar target_name: The target name of the output. It is optional and default to name. - :vartype target_name: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "target_name": {"key": "targetName", "type": "str"}, - } - - def __init__(self, *, name: str, target_name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the output defined by the skill. Required. - :paramtype name: str - :keyword target_name: The target name of the output. It is optional and default to name. - :paramtype target_name: str - """ - super().__init__(**kwargs) - self.name = name - self.target_name = target_name - - -class PathHierarchyTokenizerV2(LexicalTokenizer): - """Tokenizer for path-like hierarchies. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar delimiter: The delimiter character to use. Default is "/". - :vartype delimiter: str - :ivar replacement: A value that, if set, replaces the delimiter character. Default is "/". - :vartype replacement: str - :ivar max_token_length: The maximum token length. Default and maximum is 300. - :vartype max_token_length: int - :ivar reverse_token_order: A value indicating whether to generate tokens in reverse order. - Default is false. - :vartype reverse_token_order: bool - :ivar number_of_tokens_to_skip: The number of initial tokens to skip. Default is 0. - :vartype number_of_tokens_to_skip: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "delimiter": {"key": "delimiter", "type": "str"}, - "replacement": {"key": "replacement", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - "reverse_token_order": {"key": "reverse", "type": "bool"}, - "number_of_tokens_to_skip": {"key": "skip", "type": "int"}, - } - - def __init__( - self, - *, - name: str, - delimiter: str = "/", - replacement: str = "/", - max_token_length: int = 300, - reverse_token_order: bool = False, - number_of_tokens_to_skip: int = 0, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword delimiter: The delimiter character to use. Default is "/". - :paramtype delimiter: str - :keyword replacement: A value that, if set, replaces the delimiter character. Default is "/". - :paramtype replacement: str - :keyword max_token_length: The maximum token length. Default and maximum is 300. - :paramtype max_token_length: int - :keyword reverse_token_order: A value indicating whether to generate tokens in reverse order. - Default is false. - :paramtype reverse_token_order: bool - :keyword number_of_tokens_to_skip: The number of initial tokens to skip. Default is 0. - :paramtype number_of_tokens_to_skip: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2" - self.delimiter = delimiter - self.replacement = replacement - self.max_token_length = max_token_length - self.reverse_token_order = reverse_token_order - self.number_of_tokens_to_skip = number_of_tokens_to_skip - - -class PatternAnalyzer(LexicalAnalyzer): - """Flexibly separates text into terms via a regular expression pattern. This analyzer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar lower_case_terms: A value indicating whether terms should be lower-cased. Default is - true. - :vartype lower_case_terms: bool - :ivar pattern: A regular expression pattern to match token separators. Default is an expression - that matches one or more non-word characters. - :vartype pattern: str - :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :vartype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "lower_case_terms": {"key": "lowercase", "type": "bool"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "str"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - lower_case_terms: bool = True, - pattern: str = r"\W+", - flags: Optional[Union[str, "_models.RegexFlags"]] = None, - stopwords: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword lower_case_terms: A value indicating whether terms should be lower-cased. Default is - true. - :paramtype lower_case_terms: bool - :keyword pattern: A regular expression pattern to match token separators. Default is an - expression that matches one or more non-word characters. - :paramtype pattern: str - :keyword flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :paramtype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :keyword stopwords: A list of stopwords. - :paramtype stopwords: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternAnalyzer" - self.lower_case_terms = lower_case_terms - self.pattern = pattern - self.flags = flags - self.stopwords = stopwords - - -class PatternCaptureTokenFilter(TokenFilter): - """Uses Java regexes to emit multiple tokens - one for each capture group in one or more patterns. - This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar patterns: A list of patterns to match against each token. Required. - :vartype patterns: list[str] - :ivar preserve_original: A value indicating whether to return the original token even if one of - the patterns matches. Default is true. - :vartype preserve_original: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "patterns": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "patterns": {"key": "patterns", "type": "[str]"}, - "preserve_original": {"key": "preserveOriginal", "type": "bool"}, - } - - def __init__(self, *, name: str, patterns: list[str], preserve_original: bool = True, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword patterns: A list of patterns to match against each token. Required. - :paramtype patterns: list[str] - :keyword preserve_original: A value indicating whether to return the original token even if one - of the patterns matches. Default is true. - :paramtype preserve_original: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternCaptureTokenFilter" - self.patterns = patterns - self.preserve_original = preserve_original - - -class PatternReplaceCharFilter(CharFilter): - """A character filter that replaces characters in the input string. It uses a regular expression - to identify character sequences to preserve and a replacement pattern to identify characters to - replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\s+(bb)", and - replacement "$1#$2", the result would be "aa#bb aa#bb". This character filter is implemented - using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of char filter. Required. - :vartype odata_type: str - :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar pattern: A regular expression pattern. Required. - :vartype pattern: str - :ivar replacement: The replacement text. Required. - :vartype replacement: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "pattern": {"required": True}, - "replacement": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "replacement": {"key": "replacement", "type": "str"}, - } - - def __init__(self, *, name: str, pattern: str, replacement: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the char filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword pattern: A regular expression pattern. Required. - :paramtype pattern: str - :keyword replacement: The replacement text. Required. - :paramtype replacement: str - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternReplaceCharFilter" - self.pattern = pattern - self.replacement = replacement - - -class PatternReplaceTokenFilter(TokenFilter): - """A character filter that replaces characters in the input string. It uses a regular expression - to identify character sequences to preserve and a replacement pattern to identify characters to - replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\s+(bb)", and - replacement "$1#$2", the result would be "aa#bb aa#bb". This token filter is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar pattern: A regular expression pattern. Required. - :vartype pattern: str - :ivar replacement: The replacement text. Required. - :vartype replacement: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "pattern": {"required": True}, - "replacement": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "replacement": {"key": "replacement", "type": "str"}, - } - - def __init__(self, *, name: str, pattern: str, replacement: str, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword pattern: A regular expression pattern. Required. - :paramtype pattern: str - :keyword replacement: The replacement text. Required. - :paramtype replacement: str - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternReplaceTokenFilter" - self.pattern = pattern - self.replacement = replacement - - -class PatternTokenizer(LexicalTokenizer): - """Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar pattern: A regular expression pattern to match token separators. Default is an expression - that matches one or more non-word characters. - :vartype pattern: str - :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :vartype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :ivar group: The zero-based ordinal of the matching group in the regular expression pattern to - extract into tokens. Use -1 if you want to use the entire pattern to split the input into - tokens, irrespective of matching groups. Default is -1. - :vartype group: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "str"}, - "group": {"key": "group", "type": "int"}, - } - - def __init__( - self, - *, - name: str, - pattern: str = r"\W+", - flags: Optional[Union[str, "_models.RegexFlags"]] = None, - group: int = -1, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword pattern: A regular expression pattern to match token separators. Default is an - expression that matches one or more non-word characters. - :paramtype pattern: str - :keyword flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", - "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". - :paramtype flags: str or ~azure.search.documents.indexes.models.RegexFlags - :keyword group: The zero-based ordinal of the matching group in the regular expression pattern - to extract into tokens. Use -1 if you want to use the entire pattern to split the input into - tokens, irrespective of matching groups. Default is -1. - :paramtype group: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PatternTokenizer" - self.pattern = pattern - self.flags = flags - self.group = group - - -class PhoneticTokenFilter(TokenFilter): - """Create tokens for phonetic matches. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar encoder: The phonetic encoder to use. Default is "metaphone". Known values are: - "metaphone", "doubleMetaphone", "soundex", "refinedSoundex", "caverphone1", "caverphone2", - "cologne", "nysiis", "koelnerPhonetik", "haasePhonetik", and "beiderMorse". - :vartype encoder: str or ~azure.search.documents.indexes.models.PhoneticEncoder - :ivar replace_original_tokens: A value indicating whether encoded tokens should replace - original tokens. If false, encoded tokens are added as synonyms. Default is true. - :vartype replace_original_tokens: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "encoder": {"key": "encoder", "type": "str"}, - "replace_original_tokens": {"key": "replace", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - encoder: Optional[Union[str, "_models.PhoneticEncoder"]] = None, - replace_original_tokens: bool = True, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword encoder: The phonetic encoder to use. Default is "metaphone". Known values are: - "metaphone", "doubleMetaphone", "soundex", "refinedSoundex", "caverphone1", "caverphone2", - "cologne", "nysiis", "koelnerPhonetik", "haasePhonetik", and "beiderMorse". - :paramtype encoder: str or ~azure.search.documents.indexes.models.PhoneticEncoder - :keyword replace_original_tokens: A value indicating whether encoded tokens should replace - original tokens. If false, encoded tokens are added as synonyms. Default is true. - :paramtype replace_original_tokens: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.PhoneticTokenFilter" - self.encoder = encoder - self.replace_original_tokens = replace_original_tokens - - -class PIIDetectionSkill(SearchIndexerSkill): - """Using the Text Analytics API, extracts personal information from an input text and gives you - the option of masking it. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar masking_mode: A parameter that provides various ways to mask the personal information - detected in the input text. Default is 'none'. Known values are: "none" and "replace". - :vartype masking_mode: str or - ~azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - :ivar pii_categories: A list of PII entity categories that should be extracted and masked. - :vartype pii_categories: list[str] - :ivar domain: If specified, will set the PII domain to include only a subset of the entity - categories. Possible values include: 'phi', 'none'. Default is 'none'. - :vartype domain: str - :ivar mask: The character used to mask the text if the maskingMode parameter is set to replace. - Default is '*'. - :vartype mask: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - "mask": {"max_length": 1}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "masking_mode": {"key": "maskingMode", "type": "str"}, - "model_version": {"key": "modelVersion", "type": "str"}, - "pii_categories": {"key": "piiCategories", "type": "[str]"}, - "domain": {"key": "domain", "type": "str"}, - "mask": {"key": "mask", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[str] = None, - minimum_precision: Optional[float] = None, - masking_mode: Optional[Union[str, "_models.PIIDetectionSkillMaskingMode"]] = None, - model_version: Optional[str] = None, - pii_categories: Optional[list[str]] = None, - domain: Optional[str] = None, - mask: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :paramtype minimum_precision: float - :keyword masking_mode: A parameter that provides various ways to mask the personal information - detected in the input text. Default is 'none'. Known values are: "none" and "replace". - :paramtype masking_mode: str or - ~azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - :keyword pii_categories: A list of PII entity categories that should be extracted and masked. - :paramtype pii_categories: list[str] - :keyword domain: If specified, will set the PII domain to include only a subset of the entity - categories. Possible values include: 'phi', 'none'. Default is 'none'. - :paramtype domain: str - :keyword mask: The character used to mask the text if the maskingMode parameter is set to - replace. Default is '*'. - :paramtype mask: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.PIIDetectionSkill" - self.default_language_code = default_language_code - self.minimum_precision = minimum_precision - self.masking_mode = masking_mode - self.model_version = model_version - self.pii_categories = pii_categories - self.domain = domain - self.mask = mask - - -class RequestOptions(_serialization.Model): - """Parameter group. - - :ivar x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :vartype x_ms_client_request_id: str - """ - - _attribute_map = { - "x_ms_client_request_id": {"key": "x-ms-client-request-id", "type": "str"}, - } - - def __init__(self, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword x_ms_client_request_id: The tracking ID sent with the request to help with debugging. - :paramtype x_ms_client_request_id: str - """ - super().__init__(**kwargs) - self.x_ms_client_request_id = x_ms_client_request_id - - -class RescoringOptions(_serialization.Model): - """Contains the options for rescoring. - - :ivar enable_rescoring: If set to true, after the initial search on the compressed vectors, the - similarity scores are recalculated using the full-precision vectors. This will improve recall - at the expense of latency. - :vartype enable_rescoring: bool - :ivar default_oversampling: Default oversampling factor. Oversampling retrieves a greater set - of potential documents to offset the resolution loss due to quantization. This increases the - set of results that will be rescored on full-precision vectors. Minimum value is 1, meaning no - oversampling (1x). This parameter can only be set when 'enableRescoring' is true. Higher values - improve recall at the expense of latency. - :vartype default_oversampling: float - :ivar rescore_storage_method: Controls the storage method for original vectors. This setting is - immutable. Known values are: "preserveOriginals" and "discardOriginals". - :vartype rescore_storage_method: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod - """ - - _attribute_map = { - "enable_rescoring": {"key": "enableRescoring", "type": "bool"}, - "default_oversampling": {"key": "defaultOversampling", "type": "float"}, - "rescore_storage_method": {"key": "rescoreStorageMethod", "type": "str"}, - } - - def __init__( - self, - *, - enable_rescoring: bool = True, - default_oversampling: Optional[float] = None, - rescore_storage_method: Optional[Union[str, "_models.VectorSearchCompressionRescoreStorageMethod"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword enable_rescoring: If set to true, after the initial search on the compressed vectors, - the similarity scores are recalculated using the full-precision vectors. This will improve - recall at the expense of latency. - :paramtype enable_rescoring: bool - :keyword default_oversampling: Default oversampling factor. Oversampling retrieves a greater - set of potential documents to offset the resolution loss due to quantization. This increases - the set of results that will be rescored on full-precision vectors. Minimum value is 1, meaning - no oversampling (1x). This parameter can only be set when 'enableRescoring' is true. Higher - values improve recall at the expense of latency. - :paramtype default_oversampling: float - :keyword rescore_storage_method: Controls the storage method for original vectors. This setting - is immutable. Known values are: "preserveOriginals" and "discardOriginals". - :paramtype rescore_storage_method: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod - """ - super().__init__(**kwargs) - self.enable_rescoring = enable_rescoring - self.default_oversampling = default_oversampling - self.rescore_storage_method = rescore_storage_method - - -class ResourceCounter(_serialization.Model): - """Represents a resource's usage and quota. - - All required parameters must be populated in order to send to server. - - :ivar usage: The resource usage amount. Required. - :vartype usage: int - :ivar quota: The resource amount quota. - :vartype quota: int - """ - - _validation = { - "usage": {"required": True}, - } - - _attribute_map = { - "usage": {"key": "usage", "type": "int"}, - "quota": {"key": "quota", "type": "int"}, - } - - def __init__(self, *, usage: int, quota: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword usage: The resource usage amount. Required. - :paramtype usage: int - :keyword quota: The resource amount quota. - :paramtype quota: int - """ - super().__init__(**kwargs) - self.usage = usage - self.quota = quota - - -class ScalarQuantizationCompression(VectorSearchCompression): - """Contains configuration options specific to the scalar quantization compression method used - during indexing and querying. - - All required parameters must be populated in order to send to server. - - :ivar compression_name: The name to associate with this particular configuration. Required. - :vartype compression_name: str - :ivar kind: The name of the kind of compression method being configured for use with vector - search. Required. Known values are: "scalarQuantization" and "binaryQuantization". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind - :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated - using compressed vectors are obtained, they will be reranked again by recalculating the - full-precision similarity scores. This will improve recall at the expense of latency. - :vartype rerank_with_original_vectors: bool - :ivar default_oversampling: Default oversampling factor. Oversampling will internally request - more documents (specified by this multiplier) in the initial search. This increases the set of - results that will be reranked using recomputed similarity scores from full-precision vectors. - Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :vartype default_oversampling: float - :ivar rescoring_options: Contains the options for rescoring. - :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the - vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :vartype truncation_dimension: int - :ivar parameters: Contains the parameters specific to Scalar Quantization. - :vartype parameters: ~azure.search.documents.indexes.models.ScalarQuantizationParameters - """ - - _validation = { - "compression_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "compression_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "rerank_with_original_vectors": {"key": "rerankWithOriginalVectors", "type": "bool"}, - "default_oversampling": {"key": "defaultOversampling", "type": "float"}, - "rescoring_options": {"key": "rescoringOptions", "type": "RescoringOptions"}, - "truncation_dimension": {"key": "truncationDimension", "type": "int"}, - "parameters": {"key": "scalarQuantizationParameters", "type": "ScalarQuantizationParameters"}, - } - - def __init__( - self, - *, - compression_name: str, - rerank_with_original_vectors: Optional[bool] = None, - default_oversampling: Optional[float] = None, - rescoring_options: Optional["_models.RescoringOptions"] = None, - truncation_dimension: Optional[int] = None, - parameters: Optional["_models.ScalarQuantizationParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword compression_name: The name to associate with this particular configuration. Required. - :paramtype compression_name: str - :keyword rerank_with_original_vectors: If set to true, once the ordered set of results - calculated using compressed vectors are obtained, they will be reranked again by recalculating - the full-precision similarity scores. This will improve recall at the expense of latency. - :paramtype rerank_with_original_vectors: bool - :keyword default_oversampling: Default oversampling factor. Oversampling will internally - request more documents (specified by this multiplier) in the initial search. This increases the - set of results that will be reranked using recomputed similarity scores from full-precision - vectors. Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :paramtype default_oversampling: float - :keyword rescoring_options: Contains the options for rescoring. - :paramtype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions - :keyword truncation_dimension: The number of dimensions to truncate the vectors to. Truncating - the vectors reduces the size of the vectors and the amount of data that needs to be transferred - during search. This can save storage cost and improve search performance at the expense of - recall. It should be only used for embeddings trained with Matryoshka Representation Learning - (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no - truncation. - :paramtype truncation_dimension: int - :keyword parameters: Contains the parameters specific to Scalar Quantization. - :paramtype parameters: ~azure.search.documents.indexes.models.ScalarQuantizationParameters - """ - super().__init__( - compression_name=compression_name, - rerank_with_original_vectors=rerank_with_original_vectors, - default_oversampling=default_oversampling, - rescoring_options=rescoring_options, - truncation_dimension=truncation_dimension, - **kwargs - ) - self.kind: str = "scalarQuantization" - self.parameters = parameters - - -class ScalarQuantizationParameters(_serialization.Model): - """Contains the parameters specific to Scalar Quantization. - - :ivar quantized_data_type: The quantized data type of compressed vector values. "int8" - :vartype quantized_data_type: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionTarget - """ - - _attribute_map = { - "quantized_data_type": {"key": "quantizedDataType", "type": "str"}, - } - - def __init__( - self, - *, - quantized_data_type: Optional[Union[str, "_models.VectorSearchCompressionTarget"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword quantized_data_type: The quantized data type of compressed vector values. "int8" - :paramtype quantized_data_type: str or - ~azure.search.documents.indexes.models.VectorSearchCompressionTarget - """ - super().__init__(**kwargs) - self.quantized_data_type = quantized_data_type - - -class ScoringProfile(_serialization.Model): - """Defines parameters for a search index that influence scoring in search queries. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the scoring profile. Required. - :vartype name: str - :ivar text_weights: Parameters that boost scoring based on text matches in certain index - fields. - :vartype text_weights: ~azure.search.documents.indexes.models.TextWeights - :ivar functions: The collection of functions that influence the scoring of documents. - :vartype functions: list[~azure.search.documents.indexes.models.ScoringFunction] - :ivar function_aggregation: A value indicating how the results of individual scoring functions - should be combined. Defaults to "Sum". Ignored if there are no scoring functions. Known values - are: "sum", "average", "minimum", "maximum", and "firstMatching". - :vartype function_aggregation: str or - ~azure.search.documents.indexes.models.ScoringFunctionAggregation - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "text_weights": {"key": "text", "type": "TextWeights"}, - "functions": {"key": "functions", "type": "[ScoringFunction]"}, - "function_aggregation": {"key": "functionAggregation", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - text_weights: Optional["_models.TextWeights"] = None, - functions: Optional[list["_models.ScoringFunction"]] = None, - function_aggregation: Optional[Union[str, "_models.ScoringFunctionAggregation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the scoring profile. Required. - :paramtype name: str - :keyword text_weights: Parameters that boost scoring based on text matches in certain index - fields. - :paramtype text_weights: ~azure.search.documents.indexes.models.TextWeights - :keyword functions: The collection of functions that influence the scoring of documents. - :paramtype functions: list[~azure.search.documents.indexes.models.ScoringFunction] - :keyword function_aggregation: A value indicating how the results of individual scoring - functions should be combined. Defaults to "Sum". Ignored if there are no scoring functions. - Known values are: "sum", "average", "minimum", "maximum", and "firstMatching". - :paramtype function_aggregation: str or - ~azure.search.documents.indexes.models.ScoringFunctionAggregation - """ - super().__init__(**kwargs) - self.name = name - self.text_weights = text_weights - self.functions = functions - self.function_aggregation = function_aggregation - - -class SearchAlias(_serialization.Model): - """Represents an index alias, which describes a mapping from the alias name to an index. The alias - name can be used in place of the index name for supported operations. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the alias. Required. - :vartype name: str - :ivar indexes: The name of the index this alias maps to. Only one index name may be specified. - Required. - :vartype indexes: list[str] - :ivar e_tag: The ETag of the alias. - :vartype e_tag: str - """ - - _validation = { - "name": {"required": True}, - "indexes": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "indexes": {"key": "indexes", "type": "[str]"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - } - - def __init__(self, *, name: str, indexes: list[str], e_tag: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the alias. Required. - :paramtype name: str - :keyword indexes: The name of the index this alias maps to. Only one index name may be - specified. Required. - :paramtype indexes: list[str] - :keyword e_tag: The ETag of the alias. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.name = name - self.indexes = indexes - self.e_tag = e_tag - - -class SearchField(_serialization.Model): - """Represents a field in an index definition, which describes the name, data type, and search - behavior of a field. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the field, which must be unique within the fields collection of the - index or parent field. Required. - :vartype name: str - :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", - "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", - "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". - :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType - :ivar key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type Edm.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is false for simple fields and null for complex fields. - :vartype key: bool - :ivar retrievable: A value indicating whether the field can be returned in a search result. You - can disable this option if you want to use a field (for example, margin) as a filter, sorting, - or scoring mechanism but do not want the field to be visible to the end user. This property - must be true for key fields, and it must be null for complex fields. This property can be - changed on existing fields. Enabling this property does not cause any increase in index storage - requirements. Default is true for simple fields, false for vector fields, and null for complex - fields. - :vartype retrievable: bool - :ivar stored: An immutable value indicating whether the field will be persisted separately on - disk to be returned in a search result. You can disable this option if you don't plan to return - the field contents in a search response to save on storage overhead. This can only be set - during index creation and only for vector fields. This property cannot be changed for existing - fields or set as false for new fields. If this property is set as false, the property - 'retrievable' must also be set to false. This property must be true or unset for key fields, - for new fields, and for non-vector fields, and it must be null for complex fields. Disabling - this property will reduce index storage requirements. The default is true for vector fields. - :vartype stored: bool - :ivar searchable: A value indicating whether the field is full-text searchable. This means it - will undergo analysis such as word-breaking during indexing. If you set a searchable field to a - value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Fields of type Edm.String or - Collection(Edm.String) are searchable by default. This property must be false for simple fields - of other non-string data types, and it must be null for complex fields. Note: searchable fields - consume extra space in your index to accommodate additional tokenized versions of the field - value for full-text searches. If you want to save space in your index and you don't need a - field to be included in searches, set searchable to false. - :vartype searchable: bool - :ivar filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so - comparisons are for exact matches only. For example, if you set such a field f to "sunny day", - $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property - must be null for complex fields. Default is true for simple fields and null for complex fields. - :vartype filterable: bool - :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default, the search engine sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. Complex fields - cannot be sortable and the sortable property must be null for such fields. The default for - sortable is true for single-valued simple fields, false for multi-valued simple fields, and - null for complex fields. - :vartype sortable: bool - :ivar facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or - Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple - fields. - :vartype facetable: bool - :ivar permission_filter: A value indicating whether the field should be used as a permission - filter. Known values are: "userIds", "groupIds", and "rbacScope". - :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :ivar analyzer: The name of the analyzer to use for the field. This option can be used only - with searchable fields and it can't be set together with either searchAnalyzer or - indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null - for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar search_analyzer: The name of the analyzer used at search time for the field. This option - can be used only with searchable fields. It must be set together with indexAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. This - analyzer can be updated on an existing field. Must be null for complex fields. Known values - are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", - "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", - "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", - "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", - "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", - "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", - "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", - "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", - "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", - "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", - "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype search_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar index_analyzer: The name of the analyzer used at indexing time for the field. This option - can be used only with searchable fields. It must be set together with searchAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. Once the - analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known - values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", - "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype index_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar normalizer: The name of the normalizer to use for the field. This option can be used only - with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it - cannot be changed for the field. Must be null for complex fields. Known values are: - "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :ivar vector_search_dimensions: The dimensionality of the vector field. - :vartype vector_search_dimensions: int - :ivar vector_search_profile_name: The name of the vector search profile that specifies the - algorithm and vectorizer to use when searching the vector field. - :vartype vector_search_profile_name: str - :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" - :vartype vector_encoding_format: str or - ~azure.search.documents.indexes.models.VectorEncodingFormat - :ivar synonym_maps: A list of the names of synonym maps to associate with this field. This - option can be used only with searchable fields. Currently only one synonym map per field is - supported. Assigning a synonym map to a field ensures that query terms targeting that field are - expanded at query-time using the rules in the synonym map. This attribute can be changed on - existing fields. Must be null or an empty collection for complex fields. - :vartype synonym_maps: list[str] - :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or - Collection(Edm.ComplexType). Must be null or empty for simple fields. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - """ - - _validation = { - "name": {"required": True}, - "type": {"required": True}, - "vector_search_dimensions": {"maximum": 4096, "minimum": 2}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "key": {"key": "key", "type": "bool"}, - "retrievable": {"key": "retrievable", "type": "bool"}, - "stored": {"key": "stored", "type": "bool"}, - "searchable": {"key": "searchable", "type": "bool"}, - "filterable": {"key": "filterable", "type": "bool"}, - "sortable": {"key": "sortable", "type": "bool"}, - "facetable": {"key": "facetable", "type": "bool"}, - "permission_filter": {"key": "permissionFilter", "type": "str"}, - "analyzer": {"key": "analyzer", "type": "str"}, - "search_analyzer": {"key": "searchAnalyzer", "type": "str"}, - "index_analyzer": {"key": "indexAnalyzer", "type": "str"}, - "normalizer": {"key": "normalizer", "type": "str"}, - "vector_search_dimensions": {"key": "dimensions", "type": "int"}, - "vector_search_profile_name": {"key": "vectorSearchProfile", "type": "str"}, - "vector_encoding_format": {"key": "vectorEncoding", "type": "str"}, - "synonym_maps": {"key": "synonymMaps", "type": "[str]"}, - "fields": {"key": "fields", "type": "[SearchField]"}, - } - - def __init__( - self, - *, - name: str, - type: Union[str, "_models.SearchFieldDataType"], - key: Optional[bool] = None, - retrievable: Optional[bool] = None, - stored: Optional[bool] = None, - searchable: Optional[bool] = None, - filterable: Optional[bool] = None, - sortable: Optional[bool] = None, - facetable: Optional[bool] = None, - permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = None, - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - search_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - index_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, - vector_search_dimensions: Optional[int] = None, - vector_search_profile_name: Optional[str] = None, - vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = None, - synonym_maps: Optional[list[str]] = None, - fields: Optional[list["_models.SearchField"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the field, which must be unique within the fields collection of the - index or parent field. Required. - :paramtype name: str - :keyword type: The data type of the field. Required. Known values are: "Edm.String", - "Edm.Int32", "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", - "Edm.GeographyPoint", "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", - and "Edm.Byte". - :paramtype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType - :keyword key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type Edm.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is false for simple fields and null for complex fields. - :paramtype key: bool - :keyword retrievable: A value indicating whether the field can be returned in a search result. - You can disable this option if you want to use a field (for example, margin) as a filter, - sorting, or scoring mechanism but do not want the field to be visible to the end user. This - property must be true for key fields, and it must be null for complex fields. This property can - be changed on existing fields. Enabling this property does not cause any increase in index - storage requirements. Default is true for simple fields, false for vector fields, and null for - complex fields. - :paramtype retrievable: bool - :keyword stored: An immutable value indicating whether the field will be persisted separately - on disk to be returned in a search result. You can disable this option if you don't plan to - return the field contents in a search response to save on storage overhead. This can only be - set during index creation and only for vector fields. This property cannot be changed for - existing fields or set as false for new fields. If this property is set as false, the property - 'retrievable' must also be set to false. This property must be true or unset for key fields, - for new fields, and for non-vector fields, and it must be null for complex fields. Disabling - this property will reduce index storage requirements. The default is true for vector fields. - :paramtype stored: bool - :keyword searchable: A value indicating whether the field is full-text searchable. This means - it will undergo analysis such as word-breaking during indexing. If you set a searchable field - to a value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Fields of type Edm.String or - Collection(Edm.String) are searchable by default. This property must be false for simple fields - of other non-string data types, and it must be null for complex fields. Note: searchable fields - consume extra space in your index to accommodate additional tokenized versions of the field - value for full-text searches. If you want to save space in your index and you don't need a - field to be included in searches, set searchable to false. - :paramtype searchable: bool - :keyword filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so - comparisons are for exact matches only. For example, if you set such a field f to "sunny day", - $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property - must be null for complex fields. Default is true for simple fields and null for complex fields. - :paramtype filterable: bool - :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default, the search engine sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. Complex fields - cannot be sortable and the sortable property must be null for such fields. The default for - sortable is true for single-valued simple fields, false for multi-valued simple fields, and - null for complex fields. - :paramtype sortable: bool - :keyword facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or - Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple - fields. - :paramtype facetable: bool - :keyword permission_filter: A value indicating whether the field should be used as a permission - filter. Known values are: "userIds", "groupIds", and "rbacScope". - :paramtype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :keyword analyzer: The name of the analyzer to use for the field. This option can be used only - with searchable fields and it can't be set together with either searchAnalyzer or - indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null - for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :paramtype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword search_analyzer: The name of the analyzer used at search time for the field. This - option can be used only with searchable fields. It must be set together with indexAnalyzer and - it cannot be set together with the analyzer option. This property cannot be set to the name of - a language analyzer; use the analyzer property instead if you need a language analyzer. This - analyzer can be updated on an existing field. Must be null for complex fields. Known values - are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", - "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", - "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", - "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", - "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", - "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", - "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", - "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", - "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", - "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", - "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :paramtype search_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword index_analyzer: The name of the analyzer used at indexing time for the field. This - option can be used only with searchable fields. It must be set together with searchAnalyzer and - it cannot be set together with the analyzer option. This property cannot be set to the name of - a language analyzer; use the analyzer property instead if you need a language analyzer. Once - the analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. - Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", - "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :paramtype index_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword normalizer: The name of the normalizer to use for the field. This option can be used - only with fields with filterable, sortable, or facetable enabled. Once the normalizer is - chosen, it cannot be changed for the field. Must be null for complex fields. Known values are: - "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :paramtype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :keyword vector_search_dimensions: The dimensionality of the vector field. - :paramtype vector_search_dimensions: int - :keyword vector_search_profile_name: The name of the vector search profile that specifies the - algorithm and vectorizer to use when searching the vector field. - :paramtype vector_search_profile_name: str - :keyword vector_encoding_format: The encoding format to interpret the field contents. - "packedBit" - :paramtype vector_encoding_format: str or - ~azure.search.documents.indexes.models.VectorEncodingFormat - :keyword synonym_maps: A list of the names of synonym maps to associate with this field. This - option can be used only with searchable fields. Currently only one synonym map per field is - supported. Assigning a synonym map to a field ensures that query terms targeting that field are - expanded at query-time using the rules in the synonym map. This attribute can be changed on - existing fields. Must be null or an empty collection for complex fields. - :paramtype synonym_maps: list[str] - :keyword fields: A list of sub-fields if this is a field of type Edm.ComplexType or - Collection(Edm.ComplexType). Must be null or empty for simple fields. - :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] - """ - super().__init__(**kwargs) - self.name = name - self.type = type - self.key = key - self.retrievable = retrievable - self.stored = stored - self.searchable = searchable - self.filterable = filterable - self.sortable = sortable - self.facetable = facetable - self.permission_filter = permission_filter - self.analyzer = analyzer - self.search_analyzer = search_analyzer - self.index_analyzer = index_analyzer - self.normalizer = normalizer - self.vector_search_dimensions = vector_search_dimensions - self.vector_search_profile_name = vector_search_profile_name - self.vector_encoding_format = vector_encoding_format - self.synonym_maps = synonym_maps - self.fields = fields - - -class SearchIndex(_serialization.Model): - """Represents a search index definition, which describes the fields and search behavior of an - index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the index. Required. - :vartype name: str - :ivar description: The description of the index. - :vartype description: str - :ivar fields: The fields of the index. Required. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - :ivar scoring_profiles: The scoring profiles for the index. - :vartype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] - :ivar default_scoring_profile: The name of the scoring profile to use if none is specified in - the query. If this property is not set and no scoring profile is specified in the query, then - default scoring (tf-idf) will be used. - :vartype default_scoring_profile: str - :ivar cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. - :vartype cors_options: ~azure.search.documents.indexes.models.CorsOptions - :ivar suggesters: The suggesters for the index. - :vartype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] - :ivar analyzers: The analyzers for the index. - :vartype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] - :ivar tokenizers: The tokenizers for the index. - :vartype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] - :ivar token_filters: The token filters for the index. - :vartype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] - :ivar char_filters: The character filters for the index. - :vartype char_filters: list[~azure.search.documents.indexes.models.CharFilter] - :ivar normalizers: The normalizers for the index. - :vartype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar similarity: The type of similarity algorithm to be used when scoring and ranking the - documents matching a search query. The similarity algorithm can only be defined at index - creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity - algorithm is used. - :vartype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm - :ivar semantic_search: Defines parameters for a search index that influence semantic - capabilities. - :vartype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch - :ivar vector_search: Contains configuration options related to vector search. - :vartype vector_search: ~azure.search.documents.indexes.models.VectorSearch - :ivar permission_filter_option: A value indicating whether permission filtering is enabled for - the index. Known values are: "enabled" and "disabled". - :vartype permission_filter_option: str or - ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption - :ivar e_tag: The ETag of the index. - :vartype e_tag: str - """ - - _validation = { - "name": {"required": True}, - "fields": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "fields": {"key": "fields", "type": "[SearchField]"}, - "scoring_profiles": {"key": "scoringProfiles", "type": "[ScoringProfile]"}, - "default_scoring_profile": {"key": "defaultScoringProfile", "type": "str"}, - "cors_options": {"key": "corsOptions", "type": "CorsOptions"}, - "suggesters": {"key": "suggesters", "type": "[SearchSuggester]"}, - "analyzers": {"key": "analyzers", "type": "[LexicalAnalyzer]"}, - "tokenizers": {"key": "tokenizers", "type": "[LexicalTokenizer]"}, - "token_filters": {"key": "tokenFilters", "type": "[TokenFilter]"}, - "char_filters": {"key": "charFilters", "type": "[CharFilter]"}, - "normalizers": {"key": "normalizers", "type": "[LexicalNormalizer]"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "similarity": {"key": "similarity", "type": "SimilarityAlgorithm"}, - "semantic_search": {"key": "semantic", "type": "SemanticSearch"}, - "vector_search": {"key": "vectorSearch", "type": "VectorSearch"}, - "permission_filter_option": {"key": "permissionFilterOption", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - fields: list["_models.SearchField"], - description: Optional[str] = None, - scoring_profiles: Optional[list["_models.ScoringProfile"]] = None, - default_scoring_profile: Optional[str] = None, - cors_options: Optional["_models.CorsOptions"] = None, - suggesters: Optional[list["_models.SearchSuggester"]] = None, - analyzers: Optional[list["_models.LexicalAnalyzer"]] = None, - tokenizers: Optional[list["_models.LexicalTokenizer"]] = None, - token_filters: Optional[list["_models.TokenFilter"]] = None, - char_filters: Optional[list["_models.CharFilter"]] = None, - normalizers: Optional[list["_models.LexicalNormalizer"]] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - similarity: Optional["_models.SimilarityAlgorithm"] = None, - semantic_search: Optional["_models.SemanticSearch"] = None, - vector_search: Optional["_models.VectorSearch"] = None, - permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = None, - e_tag: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the index. Required. - :paramtype name: str - :keyword description: The description of the index. - :paramtype description: str - :keyword fields: The fields of the index. Required. - :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] - :keyword scoring_profiles: The scoring profiles for the index. - :paramtype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] - :keyword default_scoring_profile: The name of the scoring profile to use if none is specified - in the query. If this property is not set and no scoring profile is specified in the query, - then default scoring (tf-idf) will be used. - :paramtype default_scoring_profile: str - :keyword cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. - :paramtype cors_options: ~azure.search.documents.indexes.models.CorsOptions - :keyword suggesters: The suggesters for the index. - :paramtype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] - :keyword analyzers: The analyzers for the index. - :paramtype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] - :keyword tokenizers: The tokenizers for the index. - :paramtype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] - :keyword token_filters: The token filters for the index. - :paramtype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] - :keyword char_filters: The character filters for the index. - :paramtype char_filters: list[~azure.search.documents.indexes.models.CharFilter] - :keyword normalizers: The normalizers for the index. - :paramtype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword similarity: The type of similarity algorithm to be used when scoring and ranking the - documents matching a search query. The similarity algorithm can only be defined at index - creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity - algorithm is used. - :paramtype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm - :keyword semantic_search: Defines parameters for a search index that influence semantic - capabilities. - :paramtype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch - :keyword vector_search: Contains configuration options related to vector search. - :paramtype vector_search: ~azure.search.documents.indexes.models.VectorSearch - :keyword permission_filter_option: A value indicating whether permission filtering is enabled - for the index. Known values are: "enabled" and "disabled". - :paramtype permission_filter_option: str or - ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption - :keyword e_tag: The ETag of the index. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.fields = fields - self.scoring_profiles = scoring_profiles - self.default_scoring_profile = default_scoring_profile - self.cors_options = cors_options - self.suggesters = suggesters - self.analyzers = analyzers - self.tokenizers = tokenizers - self.token_filters = token_filters - self.char_filters = char_filters - self.normalizers = normalizers - self.encryption_key = encryption_key - self.similarity = similarity - self.semantic_search = semantic_search - self.vector_search = vector_search - self.permission_filter_option = permission_filter_option - self.e_tag = e_tag - - -class SearchIndexer(_serialization.Model): - """Represents an indexer. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the indexer. Required. - :vartype name: str - :ivar description: The description of the indexer. - :vartype description: str - :ivar data_source_name: The name of the datasource from which this indexer reads data. - Required. - :vartype data_source_name: str - :ivar skillset_name: The name of the skillset executing with this indexer. - :vartype skillset_name: str - :ivar target_index_name: The name of the index to which this indexer writes data. Required. - :vartype target_index_name: str - :ivar schedule: The schedule for this indexer. - :vartype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :ivar parameters: Parameters for indexer execution. - :vartype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :ivar field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :vartype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar output_field_mappings: Output field mappings are applied after enrichment and immediately - before indexing. - :vartype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar is_disabled: A value indicating whether the indexer is disabled. Default is false. - :vartype is_disabled: bool - :ivar e_tag: The ETag of the indexer. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar cache: Adds caching to an enrichment pipeline to allow for incremental modification steps - without having to rebuild the index every time. - :vartype cache: ~azure.search.documents.indexes.models.SearchIndexerCache - """ - - _validation = { - "name": {"required": True}, - "data_source_name": {"required": True}, - "target_index_name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "data_source_name": {"key": "dataSourceName", "type": "str"}, - "skillset_name": {"key": "skillsetName", "type": "str"}, - "target_index_name": {"key": "targetIndexName", "type": "str"}, - "schedule": {"key": "schedule", "type": "IndexingSchedule"}, - "parameters": {"key": "parameters", "type": "IndexingParameters"}, - "field_mappings": {"key": "fieldMappings", "type": "[FieldMapping]"}, - "output_field_mappings": {"key": "outputFieldMappings", "type": "[FieldMapping]"}, - "is_disabled": {"key": "disabled", "type": "bool"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "cache": {"key": "cache", "type": "SearchIndexerCache"}, - } - - def __init__( - self, - *, - name: str, - data_source_name: str, - target_index_name: str, - description: Optional[str] = None, - skillset_name: Optional[str] = None, - schedule: Optional["_models.IndexingSchedule"] = None, - parameters: Optional["_models.IndexingParameters"] = None, - field_mappings: Optional[list["_models.FieldMapping"]] = None, - output_field_mappings: Optional[list["_models.FieldMapping"]] = None, - is_disabled: bool = False, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - cache: Optional["_models.SearchIndexerCache"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the indexer. Required. - :paramtype name: str - :keyword description: The description of the indexer. - :paramtype description: str - :keyword data_source_name: The name of the datasource from which this indexer reads data. - Required. - :paramtype data_source_name: str - :keyword skillset_name: The name of the skillset executing with this indexer. - :paramtype skillset_name: str - :keyword target_index_name: The name of the index to which this indexer writes data. Required. - :paramtype target_index_name: str - :keyword schedule: The schedule for this indexer. - :paramtype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :keyword parameters: Parameters for indexer execution. - :paramtype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :keyword field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :paramtype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword output_field_mappings: Output field mappings are applied after enrichment and - immediately before indexing. - :paramtype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword is_disabled: A value indicating whether the indexer is disabled. Default is false. - :paramtype is_disabled: bool - :keyword e_tag: The ETag of the indexer. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword cache: Adds caching to an enrichment pipeline to allow for incremental modification - steps without having to rebuild the index every time. - :paramtype cache: ~azure.search.documents.indexes.models.SearchIndexerCache - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.data_source_name = data_source_name - self.skillset_name = skillset_name - self.target_index_name = target_index_name - self.schedule = schedule - self.parameters = parameters - self.field_mappings = field_mappings - self.output_field_mappings = output_field_mappings - self.is_disabled = is_disabled - self.e_tag = e_tag - self.encryption_key = encryption_key - self.cache = cache - - -class SearchIndexerCache(_serialization.Model): - """SearchIndexerCache. - - :ivar id: A guid for the SearchIndexerCache. - :vartype id: str - :ivar storage_connection_string: The connection string to the storage account where the cache - data will be persisted. - :vartype storage_connection_string: str - :ivar enable_reprocessing: Specifies whether incremental reprocessing is enabled. - :vartype enable_reprocessing: bool - :ivar identity: The user-assigned managed identity used for connections to the enrichment - cache. If the connection string indicates an identity (ResourceId) and it's not specified, the - system-assigned managed identity is used. On updates to the indexer, if the identity is - unspecified, the value remains unchanged. If set to "none", the value of this property is - cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "storage_connection_string": {"key": "storageConnectionString", "type": "str"}, - "enable_reprocessing": {"key": "enableReprocessing", "type": "bool"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - storage_connection_string: Optional[str] = None, - enable_reprocessing: Optional[bool] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: A guid for the SearchIndexerCache. - :paramtype id: str - :keyword storage_connection_string: The connection string to the storage account where the - cache data will be persisted. - :paramtype storage_connection_string: str - :keyword enable_reprocessing: Specifies whether incremental reprocessing is enabled. - :paramtype enable_reprocessing: bool - :keyword identity: The user-assigned managed identity used for connections to the enrichment - cache. If the connection string indicates an identity (ResourceId) and it's not specified, the - system-assigned managed identity is used. On updates to the indexer, if the identity is - unspecified, the value remains unchanged. If set to "none", the value of this property is - cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.id = id - self.storage_connection_string = storage_connection_string - self.enable_reprocessing = enable_reprocessing - self.identity = identity - - -class SearchIndexerDataContainer(_serialization.Model): - """Represents information about the entity (such as Azure SQL table or CosmosDB collection) that - will be indexed. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the table or view (for Azure SQL data source) or collection (for - CosmosDB data source) that will be indexed. Required. - :vartype name: str - :ivar query: A query that is applied to this data container. The syntax and meaning of this - parameter is datasource-specific. Not supported by Azure SQL datasources. - :vartype query: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "query": {"key": "query", "type": "str"}, - } - - def __init__(self, *, name: str, query: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the table or view (for Azure SQL data source) or collection (for - CosmosDB data source) that will be indexed. Required. - :paramtype name: str - :keyword query: A query that is applied to this data container. The syntax and meaning of this - parameter is datasource-specific. Not supported by Azure SQL datasources. - :paramtype query: str - """ - super().__init__(**kwargs) - self.name = name - self.query = query - - -class SearchIndexerDataIdentity(_serialization.Model): - """Abstract base type for data identities. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - SearchIndexerDataNoneIdentity, SearchIndexerDataUserAssignedIdentity - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of identity. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "#Microsoft.Azure.Search.DataNoneIdentity": "SearchIndexerDataNoneIdentity", - "#Microsoft.Azure.Search.DataUserAssignedIdentity": "SearchIndexerDataUserAssignedIdentity", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class SearchIndexerDataNoneIdentity(SearchIndexerDataIdentity): - """Clears the identity property of a datasource. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of identity. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DataNoneIdentity" - - -class SearchIndexerDataSource(_serialization.Model): - """Represents a datasource definition, which can be used to configure an indexer. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the datasource. Required. - :vartype name: str - :ivar description: The description of the datasource. - :vartype description: str - :ivar type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", - "azureblob", "azuretable", "mysql", "adlsgen2", and "onelake". - :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :ivar sub_type: A specific type of the data source, in case the resource is capable of - different modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts. - :vartype sub_type: str - :ivar credentials: Credentials for the datasource. Required. - :vartype credentials: ~azure.search.documents.indexes.models.DataSourceCredentials - :ivar container: The data container for the datasource. Required. - :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :ivar identity: An explicit managed identity to use for this datasource. If not specified and - the connection string is a managed identity, the system-assigned managed identity is used. If - not specified, the value remains unchanged. If "none" is specified, the value of this property - is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar indexer_permission_options: Ingestion options with various types of permission data. - :vartype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :ivar data_change_detection_policy: The data change detection policy for the datasource. - :vartype data_change_detection_policy: - ~azure.search.documents.indexes.models.DataChangeDetectionPolicy - :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource. - :vartype data_deletion_detection_policy: - ~azure.search.documents.indexes.models.DataDeletionDetectionPolicy - :ivar e_tag: The ETag of the data source. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition. Once you have encrypted your data source definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your datasource definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - _validation = { - "name": {"required": True}, - "type": {"required": True}, - "sub_type": {"readonly": True}, - "credentials": {"required": True}, - "container": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "sub_type": {"key": "subType", "type": "str"}, - "credentials": {"key": "credentials", "type": "DataSourceCredentials"}, - "container": {"key": "container", "type": "SearchIndexerDataContainer"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "indexer_permission_options": {"key": "indexerPermissionOptions", "type": "[str]"}, - "data_change_detection_policy": {"key": "dataChangeDetectionPolicy", "type": "DataChangeDetectionPolicy"}, - "data_deletion_detection_policy": {"key": "dataDeletionDetectionPolicy", "type": "DataDeletionDetectionPolicy"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - } - - def __init__( - self, - *, - name: str, - type: Union[str, "_models.SearchIndexerDataSourceType"], - credentials: "_models.DataSourceCredentials", - container: "_models.SearchIndexerDataContainer", - description: Optional[str] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = None, - data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = None, - data_deletion_detection_policy: Optional["_models.DataDeletionDetectionPolicy"] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the datasource. Required. - :paramtype name: str - :keyword description: The description of the datasource. - :paramtype description: str - :keyword type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", - "azureblob", "azuretable", "mysql", "adlsgen2", and "onelake". - :paramtype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :keyword credentials: Credentials for the datasource. Required. - :paramtype credentials: ~azure.search.documents.indexes.models.DataSourceCredentials - :keyword container: The data container for the datasource. Required. - :paramtype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :keyword identity: An explicit managed identity to use for this datasource. If not specified - and the connection string is a managed identity, the system-assigned managed identity is used. - If not specified, the value remains unchanged. If "none" is specified, the value of this - property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword indexer_permission_options: Ingestion options with various types of permission data. - :paramtype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :keyword data_change_detection_policy: The data change detection policy for the datasource. - :paramtype data_change_detection_policy: - ~azure.search.documents.indexes.models.DataChangeDetectionPolicy - :keyword data_deletion_detection_policy: The data deletion detection policy for the datasource. - :paramtype data_deletion_detection_policy: - ~azure.search.documents.indexes.models.DataDeletionDetectionPolicy - :keyword e_tag: The ETag of the data source. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition. Once you have encrypted your data source definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your datasource definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.type = type - self.sub_type: Optional[str] = None - self.credentials = credentials - self.container = container - self.identity = identity - self.indexer_permission_options = indexer_permission_options - self.data_change_detection_policy = data_change_detection_policy - self.data_deletion_detection_policy = data_deletion_detection_policy - self.e_tag = e_tag - self.encryption_key = encryption_key - - -class SearchIndexerDataUserAssignedIdentity(SearchIndexerDataIdentity): - """Specifies the identity for a datasource to use. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of identity. Required. - :vartype odata_type: str - :ivar resource_id: The fully qualified Azure resource Id of a user assigned managed identity - typically in the form - "/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId" - that should have been assigned to the search service. Required. - :vartype resource_id: str - """ - - _validation = { - "odata_type": {"required": True}, - "resource_id": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "resource_id": {"key": "userAssignedIdentity", "type": "str"}, - } - - def __init__(self, *, resource_id: str, **kwargs: Any) -> None: - """ - :keyword resource_id: The fully qualified Azure resource Id of a user assigned managed identity - typically in the form - "/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId" - that should have been assigned to the search service. Required. - :paramtype resource_id: str - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.DataUserAssignedIdentity" - self.resource_id = resource_id - - -class SearchIndexerError(_serialization.Model): - """Represents an item- or document-level indexing error. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar key: The key of the item for which indexing failed. - :vartype key: str - :ivar error_message: The message describing the error that occurred while processing the item. - Required. - :vartype error_message: str - :ivar status_code: The status code indicating why the indexing operation failed. Possible - values include: 400 for a malformed input document, 404 for document not found, 409 for a - version conflict, 422 when the index is temporarily unavailable, or 503 for when the service is - too busy. Required. - :vartype status_code: int - :ivar name: The name of the source at which the error originated. For example, this could refer - to a particular skill in the attached skillset. This may not be always available. - :vartype name: str - :ivar details: Additional, verbose details about the error to assist in debugging the indexer. - This may not be always available. - :vartype details: str - :ivar documentation_link: A link to a troubleshooting guide for these classes of errors. This - may not be always available. - :vartype documentation_link: str - """ - - _validation = { - "key": {"readonly": True}, - "error_message": {"required": True, "readonly": True}, - "status_code": {"required": True, "readonly": True}, - "name": {"readonly": True}, - "details": {"readonly": True}, - "documentation_link": {"readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "error_message": {"key": "errorMessage", "type": "str"}, - "status_code": {"key": "statusCode", "type": "int"}, - "name": {"key": "name", "type": "str"}, - "details": {"key": "details", "type": "str"}, - "documentation_link": {"key": "documentationLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.key: Optional[str] = None - self.error_message: Optional[str] = None - self.status_code: Optional[int] = None - self.name: Optional[str] = None - self.details: Optional[str] = None - self.documentation_link: Optional[str] = None - - -class SearchIndexerIndexProjection(_serialization.Model): - """Definition of additional projections to secondary search indexes. - - All required parameters must be populated in order to send to server. - - :ivar selectors: A list of projections to be performed to secondary search indexes. Required. - :vartype selectors: - list[~azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector] - :ivar parameters: A dictionary of index projection-specific configuration properties. Each name - is the name of a specific property. Each value must be of a primitive type. - :vartype parameters: - ~azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters - """ - - _validation = { - "selectors": {"required": True}, - } - - _attribute_map = { - "selectors": {"key": "selectors", "type": "[SearchIndexerIndexProjectionSelector]"}, - "parameters": {"key": "parameters", "type": "SearchIndexerIndexProjectionsParameters"}, - } - - def __init__( - self, - *, - selectors: list["_models.SearchIndexerIndexProjectionSelector"], - parameters: Optional["_models.SearchIndexerIndexProjectionsParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword selectors: A list of projections to be performed to secondary search indexes. - Required. - :paramtype selectors: - list[~azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector] - :keyword parameters: A dictionary of index projection-specific configuration properties. Each - name is the name of a specific property. Each value must be of a primitive type. - :paramtype parameters: - ~azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters - """ - super().__init__(**kwargs) - self.selectors = selectors - self.parameters = parameters - - -class SearchIndexerIndexProjectionSelector(_serialization.Model): - """Description for what data to store in the designated search index. - - All required parameters must be populated in order to send to server. - - :ivar target_index_name: Name of the search index to project to. Must have a key field with the - 'keyword' analyzer set. Required. - :vartype target_index_name: str - :ivar parent_key_field_name: Name of the field in the search index to map the parent document's - key value to. Must be a string field that is filterable and not the key field. Required. - :vartype parent_key_field_name: str - :ivar source_context: Source context for the projections. Represents the cardinality at which - the document will be split into multiple sub documents. Required. - :vartype source_context: str - :ivar mappings: Mappings for the projection, or which source should be mapped to which field in - the target index. Required. - :vartype mappings: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - - _validation = { - "target_index_name": {"required": True}, - "parent_key_field_name": {"required": True}, - "source_context": {"required": True}, - "mappings": {"required": True}, - } - - _attribute_map = { - "target_index_name": {"key": "targetIndexName", "type": "str"}, - "parent_key_field_name": {"key": "parentKeyFieldName", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "mappings": {"key": "mappings", "type": "[InputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - target_index_name: str, - parent_key_field_name: str, - source_context: str, - mappings: list["_models.InputFieldMappingEntry"], - **kwargs: Any - ) -> None: - """ - :keyword target_index_name: Name of the search index to project to. Must have a key field with - the 'keyword' analyzer set. Required. - :paramtype target_index_name: str - :keyword parent_key_field_name: Name of the field in the search index to map the parent - document's key value to. Must be a string field that is filterable and not the key field. - Required. - :paramtype parent_key_field_name: str - :keyword source_context: Source context for the projections. Represents the cardinality at - which the document will be split into multiple sub documents. Required. - :paramtype source_context: str - :keyword mappings: Mappings for the projection, or which source should be mapped to which field - in the target index. Required. - :paramtype mappings: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.target_index_name = target_index_name - self.parent_key_field_name = parent_key_field_name - self.source_context = source_context - self.mappings = mappings - - -class SearchIndexerIndexProjectionsParameters(_serialization.Model): - """A dictionary of index projection-specific configuration properties. Each name is the name of a - specific property. Each value must be of a primitive type. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar projection_mode: Defines behavior of the index projections in relation to the rest of the - indexer. Known values are: "skipIndexingParentDocuments" and "includeIndexingParentDocuments". - :vartype projection_mode: str or ~azure.search.documents.indexes.models.IndexProjectionMode - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "projection_mode": {"key": "projectionMode", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - projection_mode: Optional[Union[str, "_models.IndexProjectionMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword projection_mode: Defines behavior of the index projections in relation to the rest of - the indexer. Known values are: "skipIndexingParentDocuments" and - "includeIndexingParentDocuments". - :paramtype projection_mode: str or ~azure.search.documents.indexes.models.IndexProjectionMode - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.projection_mode = projection_mode - - -class SearchIndexerKnowledgeStore(_serialization.Model): - """Definition of additional projections to azure blob, table, or files, of enriched data. - - All required parameters must be populated in order to send to server. - - :ivar storage_connection_string: The connection string to the storage account projections will - be stored in. Required. - :vartype storage_connection_string: str - :ivar projections: A list of additional projections to perform during indexing. Required. - :vartype projections: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection] - :ivar identity: The user-assigned managed identity used for connections to Azure Storage when - writing knowledge store projections. If the connection string indicates an identity - (ResourceId) and it's not specified, the system-assigned managed identity is used. On updates - to the indexer, if the identity is unspecified, the value remains unchanged. If set to "none", - the value of this property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar parameters: A dictionary of knowledge store-specific configuration properties. Each name - is the name of a specific property. Each value must be of a primitive type. - :vartype parameters: - ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters - """ - - _validation = { - "storage_connection_string": {"required": True}, - "projections": {"required": True}, - } - - _attribute_map = { - "storage_connection_string": {"key": "storageConnectionString", "type": "str"}, - "projections": {"key": "projections", "type": "[SearchIndexerKnowledgeStoreProjection]"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - "parameters": {"key": "parameters", "type": "SearchIndexerKnowledgeStoreParameters"}, - } - - def __init__( - self, - *, - storage_connection_string: str, - projections: list["_models.SearchIndexerKnowledgeStoreProjection"], - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - parameters: Optional["_models.SearchIndexerKnowledgeStoreParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword storage_connection_string: The connection string to the storage account projections - will be stored in. Required. - :paramtype storage_connection_string: str - :keyword projections: A list of additional projections to perform during indexing. Required. - :paramtype projections: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection] - :keyword identity: The user-assigned managed identity used for connections to Azure Storage - when writing knowledge store projections. If the connection string indicates an identity - (ResourceId) and it's not specified, the system-assigned managed identity is used. On updates - to the indexer, if the identity is unspecified, the value remains unchanged. If set to "none", - the value of this property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :keyword parameters: A dictionary of knowledge store-specific configuration properties. Each - name is the name of a specific property. Each value must be of a primitive type. - :paramtype parameters: - ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters - """ - super().__init__(**kwargs) - self.storage_connection_string = storage_connection_string - self.projections = projections - self.identity = identity - self.parameters = parameters - - -class SearchIndexerKnowledgeStoreProjectionSelector(_serialization.Model): # pylint: disable=name-too-long - """Abstract class to share properties between concrete selectors. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - - _attribute_map = { - "reference_key_name": {"key": "referenceKeyName", "type": "str"}, - "generated_key_name": {"key": "generatedKeyName", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reference_key_name: Name of reference key to different projection. - :paramtype reference_key_name: str - :keyword generated_key_name: Name of generated key to store projection under. - :paramtype generated_key_name: str - :keyword source: Source data to project. - :paramtype source: str - :keyword source_context: Source context for complex projections. - :paramtype source_context: str - :keyword inputs: Nested inputs for complex projections. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - """ - super().__init__(**kwargs) - self.reference_key_name = reference_key_name - self.generated_key_name = generated_key_name - self.source = source - self.source_context = source_context - self.inputs = inputs - - -class SearchIndexerKnowledgeStoreBlobProjectionSelector( - SearchIndexerKnowledgeStoreProjectionSelector -): # pylint: disable=name-too-long - """Abstract class to share properties between concrete selectors. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar storage_container: Blob container to store projections in. Required. - :vartype storage_container: str - """ - - _validation = { - "storage_container": {"required": True}, - } - - _attribute_map = { - "reference_key_name": {"key": "referenceKeyName", "type": "str"}, - "generated_key_name": {"key": "generatedKeyName", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "storage_container": {"key": "storageContainer", "type": "str"}, - } - - def __init__( - self, - *, - storage_container: str, - reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reference_key_name: Name of reference key to different projection. - :paramtype reference_key_name: str - :keyword generated_key_name: Name of generated key to store projection under. - :paramtype generated_key_name: str - :keyword source: Source data to project. - :paramtype source: str - :keyword source_context: Source context for complex projections. - :paramtype source_context: str - :keyword inputs: Nested inputs for complex projections. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword storage_container: Blob container to store projections in. Required. - :paramtype storage_container: str - """ - super().__init__( - reference_key_name=reference_key_name, - generated_key_name=generated_key_name, - source=source, - source_context=source_context, - inputs=inputs, - **kwargs - ) - self.storage_container = storage_container - - -class SearchIndexerKnowledgeStoreFileProjectionSelector( - SearchIndexerKnowledgeStoreBlobProjectionSelector -): # pylint: disable=name-too-long - """Projection definition for what data to store in Azure Files. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar storage_container: Blob container to store projections in. Required. - :vartype storage_container: str - """ - - -class SearchIndexerKnowledgeStoreObjectProjectionSelector( - SearchIndexerKnowledgeStoreBlobProjectionSelector -): # pylint: disable=name-too-long - """Projection definition for what data to store in Azure Blob. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar storage_container: Blob container to store projections in. Required. - :vartype storage_container: str - """ - - -class SearchIndexerKnowledgeStoreParameters(_serialization.Model): - """A dictionary of knowledge store-specific configuration properties. Each name is the name of a - specific property. Each value must be of a primitive type. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar synthesize_generated_key_name: Whether or not projections should synthesize a generated - key name if one isn't already present. - :vartype synthesize_generated_key_name: bool - """ - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "synthesize_generated_key_name": {"key": "synthesizeGeneratedKeyName", "type": "bool"}, - } - - def __init__( - self, - *, - additional_properties: Optional[dict[str, Any]] = None, - synthesize_generated_key_name: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword synthesize_generated_key_name: Whether or not projections should synthesize a - generated key name if one isn't already present. - :paramtype synthesize_generated_key_name: bool - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.synthesize_generated_key_name = synthesize_generated_key_name - - -class SearchIndexerKnowledgeStoreProjection(_serialization.Model): - """Container object for various projection selectors. - - :ivar tables: Projections to Azure Table storage. - :vartype tables: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector] - :ivar objects: Projections to Azure Blob storage. - :vartype objects: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector] - :ivar files: Projections to Azure File storage. - :vartype files: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector] - """ - - _attribute_map = { - "tables": {"key": "tables", "type": "[SearchIndexerKnowledgeStoreTableProjectionSelector]"}, - "objects": {"key": "objects", "type": "[SearchIndexerKnowledgeStoreObjectProjectionSelector]"}, - "files": {"key": "files", "type": "[SearchIndexerKnowledgeStoreFileProjectionSelector]"}, - } - - def __init__( - self, - *, - tables: Optional[list["_models.SearchIndexerKnowledgeStoreTableProjectionSelector"]] = None, - objects: Optional[list["_models.SearchIndexerKnowledgeStoreObjectProjectionSelector"]] = None, - files: Optional[list["_models.SearchIndexerKnowledgeStoreFileProjectionSelector"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword tables: Projections to Azure Table storage. - :paramtype tables: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector] - :keyword objects: Projections to Azure Blob storage. - :paramtype objects: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector] - :keyword files: Projections to Azure File storage. - :paramtype files: - list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector] - """ - super().__init__(**kwargs) - self.tables = tables - self.objects = objects - self.files = files - - -class SearchIndexerKnowledgeStoreTableProjectionSelector( - SearchIndexerKnowledgeStoreProjectionSelector -): # pylint: disable=name-too-long - """Description for what data to store in Azure Tables. - - All required parameters must be populated in order to send to server. - - :ivar reference_key_name: Name of reference key to different projection. - :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str - :ivar source: Source data to project. - :vartype source: str - :ivar source_context: Source context for complex projections. - :vartype source_context: str - :ivar inputs: Nested inputs for complex projections. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar table_name: Name of the Azure table to store projected data in. Required. - :vartype table_name: str - """ - - _validation = { - "table_name": {"required": True}, - } - - _attribute_map = { - "reference_key_name": {"key": "referenceKeyName", "type": "str"}, - "generated_key_name": {"key": "generatedKeyName", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "source_context": {"key": "sourceContext", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "table_name": {"key": "tableName", "type": "str"}, - } - - def __init__( - self, - *, - table_name: str, - reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, - source: Optional[str] = None, - source_context: Optional[str] = None, - inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reference_key_name: Name of reference key to different projection. - :paramtype reference_key_name: str - :keyword generated_key_name: Name of generated key to store projection under. - :paramtype generated_key_name: str - :keyword source: Source data to project. - :paramtype source: str - :keyword source_context: Source context for complex projections. - :paramtype source_context: str - :keyword inputs: Nested inputs for complex projections. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword table_name: Name of the Azure table to store projected data in. Required. - :paramtype table_name: str - """ - super().__init__( - reference_key_name=reference_key_name, - generated_key_name=generated_key_name, - source=source, - source_context=source_context, - inputs=inputs, - **kwargs - ) - self.table_name = table_name - - -class SearchIndexerLimits(_serialization.Model): - """SearchIndexerLimits. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar max_run_time: The maximum duration that the indexer is permitted to run for one - execution. - :vartype max_run_time: ~datetime.timedelta - :ivar max_document_extraction_size: The maximum size of a document, in bytes, which will be - considered valid for indexing. - :vartype max_document_extraction_size: int - :ivar max_document_content_characters_to_extract: The maximum number of characters that will be - extracted from a document picked up for indexing. - :vartype max_document_content_characters_to_extract: int - """ - - _validation = { - "max_run_time": {"readonly": True}, - "max_document_extraction_size": {"readonly": True}, - "max_document_content_characters_to_extract": {"readonly": True}, - } - - _attribute_map = { - "max_run_time": {"key": "maxRunTime", "type": "duration"}, - "max_document_extraction_size": {"key": "maxDocumentExtractionSize", "type": "int"}, - "max_document_content_characters_to_extract": {"key": "maxDocumentContentCharactersToExtract", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.max_run_time: Optional[datetime.timedelta] = None - self.max_document_extraction_size: Optional[int] = None - self.max_document_content_characters_to_extract: Optional[int] = None - - -class SearchIndexerSkillset(_serialization.Model): - """A list of skills. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the skillset. Required. - :vartype name: str - :ivar description: The description of the skillset. - :vartype description: str - :ivar skills: A list of skills in the skillset. Required. - :vartype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] - :ivar cognitive_services_account: Details about the Azure AI service to be used when running - skills. - :vartype cognitive_services_account: - ~azure.search.documents.indexes.models.CognitiveServicesAccount - :ivar knowledge_store: Definition of additional projections to Azure blob, table, or files, of - enriched data. - :vartype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore - :ivar index_projection: Definition of additional projections to secondary search index(es). - :vartype index_projection: ~azure.search.documents.indexes.models.SearchIndexerIndexProjection - :ivar e_tag: The ETag of the skillset. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your skillset - definition when you want full assurance that no one, not even Microsoft, can decrypt your - skillset definition. Once you have encrypted your skillset definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your skillset definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - _validation = { - "name": {"required": True}, - "skills": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "skills": {"key": "skills", "type": "[SearchIndexerSkill]"}, - "cognitive_services_account": {"key": "cognitiveServices", "type": "CognitiveServicesAccount"}, - "knowledge_store": {"key": "knowledgeStore", "type": "SearchIndexerKnowledgeStore"}, - "index_projection": {"key": "indexProjections", "type": "SearchIndexerIndexProjection"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - } - - def __init__( - self, - *, - name: str, - skills: list["_models.SearchIndexerSkill"], - description: Optional[str] = None, - cognitive_services_account: Optional["_models.CognitiveServicesAccount"] = None, - knowledge_store: Optional["_models.SearchIndexerKnowledgeStore"] = None, - index_projection: Optional["_models.SearchIndexerIndexProjection"] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skillset. Required. - :paramtype name: str - :keyword description: The description of the skillset. - :paramtype description: str - :keyword skills: A list of skills in the skillset. Required. - :paramtype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] - :keyword cognitive_services_account: Details about the Azure AI service to be used when running - skills. - :paramtype cognitive_services_account: - ~azure.search.documents.indexes.models.CognitiveServicesAccount - :keyword knowledge_store: Definition of additional projections to Azure blob, table, or files, - of enriched data. - :paramtype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore - :keyword index_projection: Definition of additional projections to secondary search index(es). - :paramtype index_projection: - ~azure.search.documents.indexes.models.SearchIndexerIndexProjection - :keyword e_tag: The ETag of the skillset. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your skillset - definition when you want full assurance that no one, not even Microsoft, can decrypt your - skillset definition. Once you have encrypted your skillset definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your skillset definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.skills = skills - self.cognitive_services_account = cognitive_services_account - self.knowledge_store = knowledge_store - self.index_projection = index_projection - self.e_tag = e_tag - self.encryption_key = encryption_key - - -class SearchIndexerStatus(_serialization.Model): - """Represents the current status and execution history of an indexer. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the indexer. Required. - :vartype name: str - :ivar status: Overall indexer status. Required. Known values are: "unknown", "error", and - "running". - :vartype status: str or ~azure.search.documents.indexes.models.IndexerStatus - :ivar last_result: The result of the most recent or an in-progress indexer execution. - :vartype last_result: ~azure.search.documents.indexes.models.IndexerExecutionResult - :ivar execution_history: History of the recent indexer executions, sorted in reverse - chronological order. Required. - :vartype execution_history: list[~azure.search.documents.indexes.models.IndexerExecutionResult] - :ivar limits: The execution limits for the indexer. Required. - :vartype limits: ~azure.search.documents.indexes.models.SearchIndexerLimits - :ivar current_state: All of the state that defines and dictates the indexer's current - execution. - :vartype current_state: ~azure.search.documents.indexes.models.IndexerCurrentState - """ - - _validation = { - "name": {"required": True, "readonly": True}, - "status": {"required": True, "readonly": True}, - "last_result": {"readonly": True}, - "execution_history": {"required": True, "readonly": True}, - "limits": {"required": True, "readonly": True}, - "current_state": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "last_result": {"key": "lastResult", "type": "IndexerExecutionResult"}, - "execution_history": {"key": "executionHistory", "type": "[IndexerExecutionResult]"}, - "limits": {"key": "limits", "type": "SearchIndexerLimits"}, - "current_state": {"key": "currentState", "type": "IndexerCurrentState"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name: Optional[str] = None - self.status: Optional[Union[str, "_models.IndexerStatus"]] = None - self.last_result: Optional["_models.IndexerExecutionResult"] = None - self.execution_history: Optional[list["_models.IndexerExecutionResult"]] = None - self.limits: Optional["_models.SearchIndexerLimits"] = None - self.current_state: Optional["_models.IndexerCurrentState"] = None - - -class SearchIndexerWarning(_serialization.Model): - """Represents an item-level warning. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar key: The key of the item which generated a warning. - :vartype key: str - :ivar message: The message describing the warning that occurred while processing the item. - Required. - :vartype message: str - :ivar name: The name of the source at which the warning originated. For example, this could - refer to a particular skill in the attached skillset. This may not be always available. - :vartype name: str - :ivar details: Additional, verbose details about the warning to assist in debugging the - indexer. This may not be always available. - :vartype details: str - :ivar documentation_link: A link to a troubleshooting guide for these classes of warnings. This - may not be always available. - :vartype documentation_link: str - """ - - _validation = { - "key": {"readonly": True}, - "message": {"required": True, "readonly": True}, - "name": {"readonly": True}, - "details": {"readonly": True}, - "documentation_link": {"readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "details": {"key": "details", "type": "str"}, - "documentation_link": {"key": "documentationLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.key: Optional[str] = None - self.message: Optional[str] = None - self.name: Optional[str] = None - self.details: Optional[str] = None - self.documentation_link: Optional[str] = None - - -class SearchIndexKnowledgeSource(KnowledgeSource): - """Knowledge Source targeting a search index. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the knowledge source. Required. - :vartype name: str - :ivar description: Optional user-defined description. - :vartype description: str - :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex" and - "azureBlob". - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the agent. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar search_index_parameters: The parameters for the knowledge source. Required. - :vartype search_index_parameters: - ~azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters - """ - - _validation = { - "name": {"required": True}, - "kind": {"required": True}, - "search_index_parameters": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "search_index_parameters": {"key": "searchIndexParameters", "type": "SearchIndexKnowledgeSourceParameters"}, - } - - def __init__( - self, - *, - name: str, - search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters", - description: Optional[str] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the knowledge source. Required. - :paramtype name: str - :keyword description: Optional user-defined description. - :paramtype description: str - :keyword e_tag: The ETag of the agent. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your agent definition - when you want full assurance that no one, not even Microsoft, can decrypt them. Once you have - encrypted your agent definition, it will always remain encrypted. The search service will - ignore attempts to set this property to null. You can change this property as needed if you - want to rotate your encryption key; Your agent definition will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword search_index_parameters: The parameters for the knowledge source. Required. - :paramtype search_index_parameters: - ~azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters - """ - super().__init__(name=name, description=description, e_tag=e_tag, encryption_key=encryption_key, **kwargs) - self.kind: str = "searchIndex" - self.search_index_parameters = search_index_parameters - - -class SearchIndexKnowledgeSourceParameters(_serialization.Model): - """Parameters for search index knowledge source. - - All required parameters must be populated in order to send to server. - - :ivar search_index_name: The name of the Search index. Required. - :vartype search_index_name: str - :ivar source_data_select: Used to request additional fields for referenced source data. - :vartype source_data_select: str - """ - - _validation = { - "search_index_name": {"required": True}, - } - - _attribute_map = { - "search_index_name": {"key": "searchIndexName", "type": "str"}, - "source_data_select": {"key": "sourceDataSelect", "type": "str"}, - } - - def __init__(self, *, search_index_name: str, source_data_select: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword search_index_name: The name of the Search index. Required. - :paramtype search_index_name: str - :keyword source_data_select: Used to request additional fields for referenced source data. - :paramtype source_data_select: str - """ - super().__init__(**kwargs) - self.search_index_name = search_index_name - self.source_data_select = source_data_select - - -class SearchResourceEncryptionKey(_serialization.Model): - """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be - used to encrypt or decrypt data-at-rest, such as indexes and synonym maps. - - All required parameters must be populated in order to send to server. - - :ivar key_name: The name of your Azure Key Vault key to be used to encrypt your data at rest. - Required. - :vartype key_name: str - :ivar key_version: The version of your Azure Key Vault key to be used to encrypt your data at - rest. - :vartype key_version: str - :ivar vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that contains - the key to be used to encrypt your data at rest. An example URI might be - ``https://my-keyvault-name.vault.azure.net``. Required. - :vartype vault_uri: str - :ivar access_credentials: Optional Azure Active Directory credentials used for accessing your - Azure Key Vault. Not required if using managed identity instead. - :vartype access_credentials: - ~azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials - :ivar identity: An explicit managed identity to use for this encryption key. If not specified - and the access credentials property is null, the system-assigned managed identity is used. On - update to the resource, if the explicit identity is unspecified, it remains unchanged. If - "none" is specified, the value of this property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _validation = { - "key_name": {"required": True}, - "vault_uri": {"required": True}, - } - - _attribute_map = { - "key_name": {"key": "keyVaultKeyName", "type": "str"}, - "key_version": {"key": "keyVaultKeyVersion", "type": "str"}, - "vault_uri": {"key": "keyVaultUri", "type": "str"}, - "access_credentials": {"key": "accessCredentials", "type": "AzureActiveDirectoryApplicationCredentials"}, - "identity": {"key": "identity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - key_name: str, - vault_uri: str, - key_version: Optional[str] = None, - access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = None, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword key_name: The name of your Azure Key Vault key to be used to encrypt your data at - rest. Required. - :paramtype key_name: str - :keyword key_version: The version of your Azure Key Vault key to be used to encrypt your data - at rest. - :paramtype key_version: str - :keyword vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that - contains the key to be used to encrypt your data at rest. An example URI might be - ``https://my-keyvault-name.vault.azure.net``. Required. - :paramtype vault_uri: str - :keyword access_credentials: Optional Azure Active Directory credentials used for accessing - your Azure Key Vault. Not required if using managed identity instead. - :paramtype access_credentials: - ~azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials - :keyword identity: An explicit managed identity to use for this encryption key. If not - specified and the access credentials property is null, the system-assigned managed identity is - used. On update to the resource, if the explicit identity is unspecified, it remains unchanged. - If "none" is specified, the value of this property is cleared. - :paramtype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.key_name = key_name - self.key_version = key_version - self.vault_uri = vault_uri - self.access_credentials = access_credentials - self.identity = identity - - -class SearchServiceCounters(_serialization.Model): - """Represents service-level resource counters and quotas. - - All required parameters must be populated in order to send to server. - - :ivar alias_counter: Total number of aliases. Required. - :vartype alias_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar document_counter: Total number of documents across all indexes in the service. Required. - :vartype document_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar index_counter: Total number of indexes. Required. - :vartype index_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar indexer_counter: Total number of indexers. Required. - :vartype indexer_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar data_source_counter: Total number of data sources. Required. - :vartype data_source_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar storage_size_counter: Total size of used storage in bytes. Required. - :vartype storage_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar synonym_map_counter: Total number of synonym maps. Required. - :vartype synonym_map_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar skillset_counter: Total number of skillsets. Required. - :vartype skillset_counter: ~azure.search.documents.indexes.models.ResourceCounter - :ivar vector_index_size_counter: Total memory consumption of all vector indexes within the - service, in bytes. Required. - :vartype vector_index_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - """ - - _validation = { - "alias_counter": {"required": True}, - "document_counter": {"required": True}, - "index_counter": {"required": True}, - "indexer_counter": {"required": True}, - "data_source_counter": {"required": True}, - "storage_size_counter": {"required": True}, - "synonym_map_counter": {"required": True}, - "skillset_counter": {"required": True}, - "vector_index_size_counter": {"required": True}, - } - - _attribute_map = { - "alias_counter": {"key": "aliasesCount", "type": "ResourceCounter"}, - "document_counter": {"key": "documentCount", "type": "ResourceCounter"}, - "index_counter": {"key": "indexesCount", "type": "ResourceCounter"}, - "indexer_counter": {"key": "indexersCount", "type": "ResourceCounter"}, - "data_source_counter": {"key": "dataSourcesCount", "type": "ResourceCounter"}, - "storage_size_counter": {"key": "storageSize", "type": "ResourceCounter"}, - "synonym_map_counter": {"key": "synonymMaps", "type": "ResourceCounter"}, - "skillset_counter": {"key": "skillsetCount", "type": "ResourceCounter"}, - "vector_index_size_counter": {"key": "vectorIndexSize", "type": "ResourceCounter"}, - } - - def __init__( - self, - *, - alias_counter: "_models.ResourceCounter", - document_counter: "_models.ResourceCounter", - index_counter: "_models.ResourceCounter", - indexer_counter: "_models.ResourceCounter", - data_source_counter: "_models.ResourceCounter", - storage_size_counter: "_models.ResourceCounter", - synonym_map_counter: "_models.ResourceCounter", - skillset_counter: "_models.ResourceCounter", - vector_index_size_counter: "_models.ResourceCounter", - **kwargs: Any - ) -> None: - """ - :keyword alias_counter: Total number of aliases. Required. - :paramtype alias_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword document_counter: Total number of documents across all indexes in the service. - Required. - :paramtype document_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword index_counter: Total number of indexes. Required. - :paramtype index_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword indexer_counter: Total number of indexers. Required. - :paramtype indexer_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword data_source_counter: Total number of data sources. Required. - :paramtype data_source_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword storage_size_counter: Total size of used storage in bytes. Required. - :paramtype storage_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword synonym_map_counter: Total number of synonym maps. Required. - :paramtype synonym_map_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword skillset_counter: Total number of skillsets. Required. - :paramtype skillset_counter: ~azure.search.documents.indexes.models.ResourceCounter - :keyword vector_index_size_counter: Total memory consumption of all vector indexes within the - service, in bytes. Required. - :paramtype vector_index_size_counter: ~azure.search.documents.indexes.models.ResourceCounter - """ - super().__init__(**kwargs) - self.alias_counter = alias_counter - self.document_counter = document_counter - self.index_counter = index_counter - self.indexer_counter = indexer_counter - self.data_source_counter = data_source_counter - self.storage_size_counter = storage_size_counter - self.synonym_map_counter = synonym_map_counter - self.skillset_counter = skillset_counter - self.vector_index_size_counter = vector_index_size_counter - - -class SearchServiceLimits(_serialization.Model): - """Represents various service level limits. - - :ivar max_fields_per_index: The maximum allowed fields per index. - :vartype max_fields_per_index: int - :ivar max_field_nesting_depth_per_index: The maximum depth which you can nest sub-fields in an - index, including the top-level complex field. For example, a/b/c has a nesting depth of 3. - :vartype max_field_nesting_depth_per_index: int - :ivar max_complex_collection_fields_per_index: The maximum number of fields of type - Collection(Edm.ComplexType) allowed in an index. - :vartype max_complex_collection_fields_per_index: int - :ivar max_complex_objects_in_collections_per_document: The maximum number of objects in complex - collections allowed per document. - :vartype max_complex_objects_in_collections_per_document: int - :ivar max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per index. - :vartype max_storage_per_index_in_bytes: int - """ - - _attribute_map = { - "max_fields_per_index": {"key": "maxFieldsPerIndex", "type": "int"}, - "max_field_nesting_depth_per_index": {"key": "maxFieldNestingDepthPerIndex", "type": "int"}, - "max_complex_collection_fields_per_index": {"key": "maxComplexCollectionFieldsPerIndex", "type": "int"}, - "max_complex_objects_in_collections_per_document": { - "key": "maxComplexObjectsInCollectionsPerDocument", - "type": "int", - }, - "max_storage_per_index_in_bytes": {"key": "maxStoragePerIndex", "type": "int"}, - } - - def __init__( - self, - *, - max_fields_per_index: Optional[int] = None, - max_field_nesting_depth_per_index: Optional[int] = None, - max_complex_collection_fields_per_index: Optional[int] = None, - max_complex_objects_in_collections_per_document: Optional[int] = None, - max_storage_per_index_in_bytes: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword max_fields_per_index: The maximum allowed fields per index. - :paramtype max_fields_per_index: int - :keyword max_field_nesting_depth_per_index: The maximum depth which you can nest sub-fields in - an index, including the top-level complex field. For example, a/b/c has a nesting depth of 3. - :paramtype max_field_nesting_depth_per_index: int - :keyword max_complex_collection_fields_per_index: The maximum number of fields of type - Collection(Edm.ComplexType) allowed in an index. - :paramtype max_complex_collection_fields_per_index: int - :keyword max_complex_objects_in_collections_per_document: The maximum number of objects in - complex collections allowed per document. - :paramtype max_complex_objects_in_collections_per_document: int - :keyword max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per - index. - :paramtype max_storage_per_index_in_bytes: int - """ - super().__init__(**kwargs) - self.max_fields_per_index = max_fields_per_index - self.max_field_nesting_depth_per_index = max_field_nesting_depth_per_index - self.max_complex_collection_fields_per_index = max_complex_collection_fields_per_index - self.max_complex_objects_in_collections_per_document = max_complex_objects_in_collections_per_document - self.max_storage_per_index_in_bytes = max_storage_per_index_in_bytes - - -class SearchServiceStatistics(_serialization.Model): - """Response from a get service statistics request. If successful, it includes service level - counters and limits. - - All required parameters must be populated in order to send to server. - - :ivar counters: Service level resource counters. Required. - :vartype counters: ~azure.search.documents.indexes.models.SearchServiceCounters - :ivar limits: Service level general limits. Required. - :vartype limits: ~azure.search.documents.indexes.models.SearchServiceLimits - """ - - _validation = { - "counters": {"required": True}, - "limits": {"required": True}, - } - - _attribute_map = { - "counters": {"key": "counters", "type": "SearchServiceCounters"}, - "limits": {"key": "limits", "type": "SearchServiceLimits"}, - } - - def __init__( - self, *, counters: "_models.SearchServiceCounters", limits: "_models.SearchServiceLimits", **kwargs: Any - ) -> None: - """ - :keyword counters: Service level resource counters. Required. - :paramtype counters: ~azure.search.documents.indexes.models.SearchServiceCounters - :keyword limits: Service level general limits. Required. - :paramtype limits: ~azure.search.documents.indexes.models.SearchServiceLimits - """ - super().__init__(**kwargs) - self.counters = counters - self.limits = limits - - -class SearchSuggester(_serialization.Model): - """Defines how the Suggest API should apply to a group of fields in the index. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the suggester. Required. - :vartype name: str - :ivar search_mode: A value indicating the capabilities of the suggester. Required. Default - value is "analyzingInfixMatching". - :vartype search_mode: str - :ivar source_fields: The list of field names to which the suggester applies. Each field must be - searchable. Required. - :vartype source_fields: list[str] - """ - - _validation = { - "name": {"required": True}, - "search_mode": {"required": True, "constant": True}, - "source_fields": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "search_mode": {"key": "searchMode", "type": "str"}, - "source_fields": {"key": "sourceFields", "type": "[str]"}, - } - - search_mode = "analyzingInfixMatching" - - def __init__(self, *, name: str, source_fields: list[str], **kwargs: Any) -> None: - """ - :keyword name: The name of the suggester. Required. - :paramtype name: str - :keyword source_fields: The list of field names to which the suggester applies. Each field must - be searchable. Required. - :paramtype source_fields: list[str] - """ - super().__init__(**kwargs) - self.name = name - self.source_fields = source_fields - - -class SemanticConfiguration(_serialization.Model): - """Defines a specific configuration to be used in the context of semantic capabilities. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the semantic configuration. Required. - :vartype name: str - :ivar prioritized_fields: Describes the title, content, and keyword fields to be used for - semantic ranking, captions, highlights, and answers. At least one of the three sub properties - (titleField, prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required. - :vartype prioritized_fields: ~azure.search.documents.indexes.models.SemanticPrioritizedFields - :ivar ranking_order: Specifies the score type to be used for the sort order of the search - results. Known values are: "BoostedRerankerScore" and "RerankerScore". - :vartype ranking_order: str or ~azure.search.documents.indexes.models.RankingOrder - :ivar flighting_opt_in: Determines which semantic or query rewrite models to use during model - flighting/upgrades. - :vartype flighting_opt_in: bool - """ - - _validation = { - "name": {"required": True}, - "prioritized_fields": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "prioritized_fields": {"key": "prioritizedFields", "type": "SemanticPrioritizedFields"}, - "ranking_order": {"key": "rankingOrder", "type": "str"}, - "flighting_opt_in": {"key": "flightingOptIn", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - prioritized_fields: "_models.SemanticPrioritizedFields", - ranking_order: Optional[Union[str, "_models.RankingOrder"]] = None, - flighting_opt_in: bool = False, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the semantic configuration. Required. - :paramtype name: str - :keyword prioritized_fields: Describes the title, content, and keyword fields to be used for - semantic ranking, captions, highlights, and answers. At least one of the three sub properties - (titleField, prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required. - :paramtype prioritized_fields: ~azure.search.documents.indexes.models.SemanticPrioritizedFields - :keyword ranking_order: Specifies the score type to be used for the sort order of the search - results. Known values are: "BoostedRerankerScore" and "RerankerScore". - :paramtype ranking_order: str or ~azure.search.documents.indexes.models.RankingOrder - :keyword flighting_opt_in: Determines which semantic or query rewrite models to use during - model flighting/upgrades. - :paramtype flighting_opt_in: bool - """ - super().__init__(**kwargs) - self.name = name - self.prioritized_fields = prioritized_fields - self.ranking_order = ranking_order - self.flighting_opt_in = flighting_opt_in - - -class SemanticField(_serialization.Model): - """A field that is used as part of the semantic configuration. - - All required parameters must be populated in order to send to server. - - :ivar field_name: Required. - :vartype field_name: str - """ - - _validation = { - "field_name": {"required": True}, - } - - _attribute_map = { - "field_name": {"key": "fieldName", "type": "str"}, - } - - def __init__(self, *, field_name: str, **kwargs: Any) -> None: - """ - :keyword field_name: Required. - :paramtype field_name: str - """ - super().__init__(**kwargs) - self.field_name = field_name - - -class SemanticPrioritizedFields(_serialization.Model): - """Describes the title, content, and keywords fields to be used for semantic ranking, captions, - highlights, and answers. - - :ivar title_field: Defines the title field to be used for semantic ranking, captions, - highlights, and answers. If you don't have a title field in your index, leave this blank. - :vartype title_field: ~azure.search.documents.indexes.models.SemanticField - :ivar content_fields: Defines the content fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain text in - natural language form. The order of the fields in the array represents their priority. Fields - with lower priority may get truncated if the content is long. - :vartype content_fields: list[~azure.search.documents.indexes.models.SemanticField] - :ivar keywords_fields: Defines the keyword fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain a list of - keywords. The order of the fields in the array represents their priority. Fields with lower - priority may get truncated if the content is long. - :vartype keywords_fields: list[~azure.search.documents.indexes.models.SemanticField] - """ - - _attribute_map = { - "title_field": {"key": "titleField", "type": "SemanticField"}, - "content_fields": {"key": "prioritizedContentFields", "type": "[SemanticField]"}, - "keywords_fields": {"key": "prioritizedKeywordsFields", "type": "[SemanticField]"}, - } - - def __init__( - self, - *, - title_field: Optional["_models.SemanticField"] = None, - content_fields: Optional[list["_models.SemanticField"]] = None, - keywords_fields: Optional[list["_models.SemanticField"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword title_field: Defines the title field to be used for semantic ranking, captions, - highlights, and answers. If you don't have a title field in your index, leave this blank. - :paramtype title_field: ~azure.search.documents.indexes.models.SemanticField - :keyword content_fields: Defines the content fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain text in - natural language form. The order of the fields in the array represents their priority. Fields - with lower priority may get truncated if the content is long. - :paramtype content_fields: list[~azure.search.documents.indexes.models.SemanticField] - :keyword keywords_fields: Defines the keyword fields to be used for semantic ranking, captions, - highlights, and answers. For the best result, the selected fields should contain a list of - keywords. The order of the fields in the array represents their priority. Fields with lower - priority may get truncated if the content is long. - :paramtype keywords_fields: list[~azure.search.documents.indexes.models.SemanticField] - """ - super().__init__(**kwargs) - self.title_field = title_field - self.content_fields = content_fields - self.keywords_fields = keywords_fields - - -class SemanticSearch(_serialization.Model): - """Defines parameters for a search index that influence semantic capabilities. - - :ivar default_configuration_name: Allows you to set the name of a default semantic - configuration in your index, making it optional to pass it on as a query parameter every time. - :vartype default_configuration_name: str - :ivar configurations: The semantic configurations for the index. - :vartype configurations: list[~azure.search.documents.indexes.models.SemanticConfiguration] - """ - - _attribute_map = { - "default_configuration_name": {"key": "defaultConfiguration", "type": "str"}, - "configurations": {"key": "configurations", "type": "[SemanticConfiguration]"}, - } - - def __init__( - self, - *, - default_configuration_name: Optional[str] = None, - configurations: Optional[list["_models.SemanticConfiguration"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword default_configuration_name: Allows you to set the name of a default semantic - configuration in your index, making it optional to pass it on as a query parameter every time. - :paramtype default_configuration_name: str - :keyword configurations: The semantic configurations for the index. - :paramtype configurations: list[~azure.search.documents.indexes.models.SemanticConfiguration] - """ - super().__init__(**kwargs) - self.default_configuration_name = default_configuration_name - self.configurations = configurations - - -class SentimentSkill(SearchIndexerSkill): - """This skill is deprecated. Use the V3.SentimentSkill instead. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", "ru", - "es", "sv", and "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.SentimentSkillLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.SentimentSkillLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", - "ru", "es", "sv", and "tr". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.SentimentSkillLanguage - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.SentimentSkill" - self.default_language_code = default_language_code - - -class SentimentSkillV3(SearchIndexerSkill): - """Using the Text Analytics API, evaluates unstructured text and for each record, provides - sentiment labels (such as "negative", "neutral" and "positive") based on the highest confidence - score found by the service at a sentence and document-level. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - :vartype default_language_code: str - :ivar include_opinion_mining: If set to true, the skill output will include information from - Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated - assessment (adjective) in the text. Default is false. - :vartype include_opinion_mining: bool - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_opinion_mining": {"key": "includeOpinionMining", "type": "bool"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[str] = None, - include_opinion_mining: bool = False, - model_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. - :paramtype default_language_code: str - :keyword include_opinion_mining: If set to true, the skill output will include information from - Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated - assessment (adjective) in the text. Default is false. - :paramtype include_opinion_mining: bool - :keyword model_version: The version of the model to use when calling the Text Analytics - service. It will default to the latest available when not specified. We recommend you do not - specify this value unless absolutely necessary. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.V3.SentimentSkill" - self.default_language_code = default_language_code - self.include_opinion_mining = include_opinion_mining - self.model_version = model_version - - -class ShaperSkill(SearchIndexerSkill): - """A skill for reshaping the outputs. It creates a complex type to support composite fields (also - known as multipart fields). - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Util.ShaperSkill" - - -class ShingleTokenFilter(TokenFilter): - """Creates combinations of tokens as a single token. This token filter is implemented using Apache - Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_shingle_size: The maximum shingle size. Default and minimum value is 2. - :vartype max_shingle_size: int - :ivar min_shingle_size: The minimum shingle size. Default and minimum value is 2. Must be less - than the value of maxShingleSize. - :vartype min_shingle_size: int - :ivar output_unigrams: A value indicating whether the output stream will contain the input - tokens (unigrams) as well as shingles. Default is true. - :vartype output_unigrams: bool - :ivar output_unigrams_if_no_shingles: A value indicating whether to output unigrams for those - times when no shingles are available. This property takes precedence when outputUnigrams is set - to false. Default is false. - :vartype output_unigrams_if_no_shingles: bool - :ivar token_separator: The string to use when joining adjacent tokens to form a shingle. - Default is a single space (" "). - :vartype token_separator: str - :ivar filter_token: The string to insert for each position at which there is no token. Default - is an underscore ("_"). - :vartype filter_token: str - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_shingle_size": {"minimum": 2}, - "min_shingle_size": {"minimum": 2}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_shingle_size": {"key": "maxShingleSize", "type": "int"}, - "min_shingle_size": {"key": "minShingleSize", "type": "int"}, - "output_unigrams": {"key": "outputUnigrams", "type": "bool"}, - "output_unigrams_if_no_shingles": {"key": "outputUnigramsIfNoShingles", "type": "bool"}, - "token_separator": {"key": "tokenSeparator", "type": "str"}, - "filter_token": {"key": "filterToken", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - max_shingle_size: int = 2, - min_shingle_size: int = 2, - output_unigrams: bool = True, - output_unigrams_if_no_shingles: bool = False, - token_separator: str = " ", - filter_token: str = "_", - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword max_shingle_size: The maximum shingle size. Default and minimum value is 2. - :paramtype max_shingle_size: int - :keyword min_shingle_size: The minimum shingle size. Default and minimum value is 2. Must be - less than the value of maxShingleSize. - :paramtype min_shingle_size: int - :keyword output_unigrams: A value indicating whether the output stream will contain the input - tokens (unigrams) as well as shingles. Default is true. - :paramtype output_unigrams: bool - :keyword output_unigrams_if_no_shingles: A value indicating whether to output unigrams for - those times when no shingles are available. This property takes precedence when outputUnigrams - is set to false. Default is false. - :paramtype output_unigrams_if_no_shingles: bool - :keyword token_separator: The string to use when joining adjacent tokens to form a shingle. - Default is a single space (" "). - :paramtype token_separator: str - :keyword filter_token: The string to insert for each position at which there is no token. - Default is an underscore ("_"). - :paramtype filter_token: str - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.ShingleTokenFilter" - self.max_shingle_size = max_shingle_size - self.min_shingle_size = min_shingle_size - self.output_unigrams = output_unigrams - self.output_unigrams_if_no_shingles = output_unigrams_if_no_shingles - self.token_separator = token_separator - self.filter_token = filter_token - - -class SkillNames(_serialization.Model): - """SkillNames. - - :ivar skill_names: the names of skills to be reset. - :vartype skill_names: list[str] - """ - - _attribute_map = { - "skill_names": {"key": "skillNames", "type": "[str]"}, - } - - def __init__(self, *, skill_names: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword skill_names: the names of skills to be reset. - :paramtype skill_names: list[str] - """ - super().__init__(**kwargs) - self.skill_names = skill_names - - -class SnowballTokenFilter(TokenFilter): - """A filter that stems words using a Snowball-generated stemmer. This token filter is implemented - using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar language: The language to use. Required. Known values are: "armenian", "basque", - "catalan", "danish", "dutch", "english", "finnish", "french", "german", "german2", "hungarian", - "italian", "kp", "lovins", "norwegian", "porter", "portuguese", "romanian", "russian", - "spanish", "swedish", and "turkish". - :vartype language: str or ~azure.search.documents.indexes.models.SnowballTokenFilterLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "language": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__( - self, *, name: str, language: Union[str, "_models.SnowballTokenFilterLanguage"], **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword language: The language to use. Required. Known values are: "armenian", "basque", - "catalan", "danish", "dutch", "english", "finnish", "french", "german", "german2", "hungarian", - "italian", "kp", "lovins", "norwegian", "porter", "portuguese", "romanian", "russian", - "spanish", "swedish", and "turkish". - :paramtype language: str or ~azure.search.documents.indexes.models.SnowballTokenFilterLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SnowballTokenFilter" - self.language = language - - -class SoftDeleteColumnDeletionDetectionPolicy(DataDeletionDetectionPolicy): - """Defines a data deletion detection policy that implements a soft-deletion strategy. It - determines whether an item should be deleted based on the value of a designated 'soft delete' - column. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. - Required. - :vartype odata_type: str - :ivar soft_delete_column_name: The name of the column to use for soft-deletion detection. - :vartype soft_delete_column_name: str - :ivar soft_delete_marker_value: The marker value that identifies an item as deleted. - :vartype soft_delete_marker_value: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "soft_delete_column_name": {"key": "softDeleteColumnName", "type": "str"}, - "soft_delete_marker_value": {"key": "softDeleteMarkerValue", "type": "str"}, - } - - def __init__( - self, - *, - soft_delete_column_name: Optional[str] = None, - soft_delete_marker_value: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword soft_delete_column_name: The name of the column to use for soft-deletion detection. - :paramtype soft_delete_column_name: str - :keyword soft_delete_marker_value: The marker value that identifies an item as deleted. - :paramtype soft_delete_marker_value: str - """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy" - self.soft_delete_column_name = soft_delete_column_name - self.soft_delete_marker_value = soft_delete_marker_value - - -class SplitSkill(SearchIndexerSkill): - """A skill to split a string into chunks of text. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is ``en``. - Known values are: "am", "bs", "cs", "da", "de", "en", "es", "et", "fi", "fr", "he", "hi", "hr", - "hu", "id", "is", "it", "ja", "ko", "lv", "nb", "nl", "pl", "pt", "pt-br", "ru", "sk", "sl", - "sr", "sv", "tr", "ur", "zh", and "is". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.SplitSkillLanguage - :ivar text_split_mode: A value indicating which split mode to perform. Known values are: - "pages" and "sentences". - :vartype text_split_mode: str or ~azure.search.documents.indexes.models.TextSplitMode - :ivar maximum_page_length: The desired maximum page length. Default is 10000. - :vartype maximum_page_length: int - :ivar page_overlap_length: Only applicable when textSplitMode is set to 'pages'. If specified, - n+1th chunk will start with this number of characters/tokens from the end of the nth chunk. - :vartype page_overlap_length: int - :ivar maximum_pages_to_take: Only applicable when textSplitMode is set to 'pages'. If - specified, the SplitSkill will discontinue splitting after processing the first - 'maximumPagesToTake' pages, in order to improve performance when only a few initial pages are - needed from each document. - :vartype maximum_pages_to_take: int - :ivar unit: Only applies if textSplitMode is set to pages. There are two possible values. The - choice of the values will decide the length (maximumPageLength and pageOverlapLength) - measurement. The default is 'characters', which means the length will be measured by character. - Known values are: "characters" and "azureOpenAITokens". - :vartype unit: str or ~azure.search.documents.indexes.models.SplitSkillUnit - :ivar parameters: Only applies if the unit is set to azureOpenAITokens. If specified, the - splitSkill will use these parameters when performing the tokenization. The parameters are a - valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. - :vartype parameters: ~azure.search.documents.indexes.models.AzureOpenAITokenizerParameters - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "text_split_mode": {"key": "textSplitMode", "type": "str"}, - "maximum_page_length": {"key": "maximumPageLength", "type": "int"}, - "page_overlap_length": {"key": "pageOverlapLength", "type": "int"}, - "maximum_pages_to_take": {"key": "maximumPagesToTake", "type": "int"}, - "unit": {"key": "unit", "type": "str"}, - "parameters": {"key": "azureOpenAITokenizerParameters", "type": "AzureOpenAITokenizerParameters"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_language_code: Optional[Union[str, "_models.SplitSkillLanguage"]] = None, - text_split_mode: Optional[Union[str, "_models.TextSplitMode"]] = None, - maximum_page_length: Optional[int] = None, - page_overlap_length: Optional[int] = None, - maximum_pages_to_take: Optional[int] = None, - unit: Optional[Union[str, "_models.SplitSkillUnit"]] = None, - parameters: Optional["_models.AzureOpenAITokenizerParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_language_code: A value indicating which language code to use. Default is - ``en``. Known values are: "am", "bs", "cs", "da", "de", "en", "es", "et", "fi", "fr", "he", - "hi", "hr", "hu", "id", "is", "it", "ja", "ko", "lv", "nb", "nl", "pl", "pt", "pt-br", "ru", - "sk", "sl", "sr", "sv", "tr", "ur", "zh", and "is". - :paramtype default_language_code: str or - ~azure.search.documents.indexes.models.SplitSkillLanguage - :keyword text_split_mode: A value indicating which split mode to perform. Known values are: - "pages" and "sentences". - :paramtype text_split_mode: str or ~azure.search.documents.indexes.models.TextSplitMode - :keyword maximum_page_length: The desired maximum page length. Default is 10000. - :paramtype maximum_page_length: int - :keyword page_overlap_length: Only applicable when textSplitMode is set to 'pages'. If - specified, n+1th chunk will start with this number of characters/tokens from the end of the nth - chunk. - :paramtype page_overlap_length: int - :keyword maximum_pages_to_take: Only applicable when textSplitMode is set to 'pages'. If - specified, the SplitSkill will discontinue splitting after processing the first - 'maximumPagesToTake' pages, in order to improve performance when only a few initial pages are - needed from each document. - :paramtype maximum_pages_to_take: int - :keyword unit: Only applies if textSplitMode is set to pages. There are two possible values. - The choice of the values will decide the length (maximumPageLength and pageOverlapLength) - measurement. The default is 'characters', which means the length will be measured by character. - Known values are: "characters" and "azureOpenAITokens". - :paramtype unit: str or ~azure.search.documents.indexes.models.SplitSkillUnit - :keyword parameters: Only applies if the unit is set to azureOpenAITokens. If specified, the - splitSkill will use these parameters when performing the tokenization. The parameters are a - valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. - :paramtype parameters: ~azure.search.documents.indexes.models.AzureOpenAITokenizerParameters - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.SplitSkill" - self.default_language_code = default_language_code - self.text_split_mode = text_split_mode - self.maximum_page_length = maximum_page_length - self.page_overlap_length = page_overlap_length - self.maximum_pages_to_take = maximum_pages_to_take - self.unit = unit - self.parameters = parameters - - -class SqlIntegratedChangeTrackingPolicy(DataChangeDetectionPolicy): - """Defines a data change detection policy that captures changes using the Integrated Change - Tracking feature of Azure SQL Database. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy" - - -class StemmerOverrideTokenFilter(TokenFilter): - """Provides the ability to override other stemming filters with custom dictionary-based stemming. - Any dictionary-stemmed terms will be marked as keywords so that they will not be stemmed with - stemmers down the chain. Must be placed before any stemming filters. This token filter is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar rules: A list of stemming rules in the following format: "word => stem", for example: - "ran => run". Required. - :vartype rules: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "rules": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "rules": {"key": "rules", "type": "[str]"}, - } - - def __init__(self, *, name: str, rules: list[str], **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword rules: A list of stemming rules in the following format: "word => stem", for example: - "ran => run". Required. - :paramtype rules: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StemmerOverrideTokenFilter" - self.rules = rules - - -class StemmerTokenFilter(TokenFilter): - """Language specific stemming filter. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar language: The language to use. Required. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "dutchKp", - "english", "lightEnglish", "minimalEnglish", "possessiveEnglish", "porter2", "lovins", - "finnish", "lightFinnish", "french", "lightFrench", "minimalFrench", "galician", - "minimalGalician", "german", "german2", "lightGerman", "minimalGerman", "greek", "hindi", - "hungarian", "lightHungarian", "indonesian", "irish", "italian", "lightItalian", "sorani", - "latvian", "norwegian", "lightNorwegian", "minimalNorwegian", "lightNynorsk", "minimalNynorsk", - "portuguese", "lightPortuguese", "minimalPortuguese", "portugueseRslp", "romanian", "russian", - "lightRussian", "spanish", "lightSpanish", "swedish", "lightSwedish", and "turkish". - :vartype language: str or ~azure.search.documents.indexes.models.StemmerTokenFilterLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "language": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "language": {"key": "language", "type": "str"}, - } - - def __init__(self, *, name: str, language: Union[str, "_models.StemmerTokenFilterLanguage"], **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword language: The language to use. Required. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "dutchKp", - "english", "lightEnglish", "minimalEnglish", "possessiveEnglish", "porter2", "lovins", - "finnish", "lightFinnish", "french", "lightFrench", "minimalFrench", "galician", - "minimalGalician", "german", "german2", "lightGerman", "minimalGerman", "greek", "hindi", - "hungarian", "lightHungarian", "indonesian", "irish", "italian", "lightItalian", "sorani", - "latvian", "norwegian", "lightNorwegian", "minimalNorwegian", "lightNynorsk", "minimalNynorsk", - "portuguese", "lightPortuguese", "minimalPortuguese", "portugueseRslp", "romanian", "russian", - "lightRussian", "spanish", "lightSpanish", "swedish", "lightSwedish", and "turkish". - :paramtype language: str or ~azure.search.documents.indexes.models.StemmerTokenFilterLanguage - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StemmerTokenFilter" - self.language = language - - -class StopAnalyzer(LexicalAnalyzer): - """Divides text at non-letters; Applies the lowercase and stopword token filters. This analyzer is - implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of analyzer. Required. - :vartype odata_type: str - :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__(self, *, name: str, stopwords: Optional[list[str]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the analyzer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword stopwords: A list of stopwords. - :paramtype stopwords: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StopAnalyzer" - self.stopwords = stopwords - - -class StopwordsTokenFilter(TokenFilter): - """Removes stop words from a token stream. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar stopwords: The list of stopwords. This property and the stopwords list property cannot - both be set. - :vartype stopwords: list[str] - :ivar stopwords_list: A predefined list of stopwords to use. This property and the stopwords - property cannot both be set. Default is English. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", - "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", - "irish", "italian", "latvian", "norwegian", "persian", "portuguese", "romanian", "russian", - "sorani", "spanish", "swedish", "thai", and "turkish". - :vartype stopwords_list: str or ~azure.search.documents.indexes.models.StopwordsList - :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted - to lower case first. Default is false. - :vartype ignore_case: bool - :ivar remove_trailing_stop_words: A value indicating whether to ignore the last search term if - it's a stop word. Default is true. - :vartype remove_trailing_stop_words: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - "stopwords_list": {"key": "stopwordsList", "type": "str"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - "remove_trailing_stop_words": {"key": "removeTrailing", "type": "bool"}, - } - - def __init__( - self, - *, - name: str, - stopwords: Optional[list[str]] = None, - stopwords_list: Optional[Union[str, "_models.StopwordsList"]] = None, - ignore_case: bool = False, - remove_trailing_stop_words: bool = True, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword stopwords: The list of stopwords. This property and the stopwords list property cannot - both be set. - :paramtype stopwords: list[str] - :keyword stopwords_list: A predefined list of stopwords to use. This property and the stopwords - property cannot both be set. Default is English. Known values are: "arabic", "armenian", - "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", - "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", - "irish", "italian", "latvian", "norwegian", "persian", "portuguese", "romanian", "russian", - "sorani", "spanish", "swedish", "thai", and "turkish". - :paramtype stopwords_list: str or ~azure.search.documents.indexes.models.StopwordsList - :keyword ignore_case: A value indicating whether to ignore case. If true, all words are - converted to lower case first. Default is false. - :paramtype ignore_case: bool - :keyword remove_trailing_stop_words: A value indicating whether to ignore the last search term - if it's a stop word. Default is true. - :paramtype remove_trailing_stop_words: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.StopwordsTokenFilter" - self.stopwords = stopwords - self.stopwords_list = stopwords_list - self.ignore_case = ignore_case - self.remove_trailing_stop_words = remove_trailing_stop_words - - -class SynonymMap(_serialization.Model): - """Represents a synonym map definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the synonym map. Required. - :vartype name: str - :ivar format: The format of the synonym map. Only the 'solr' format is currently supported. - Required. Default value is "solr". - :vartype format: str - :ivar synonyms: A series of synonym rules in the specified synonym map format. The rules must - be separated by newlines. Required. - :vartype synonyms: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar e_tag: The ETag of the synonym map. - :vartype e_tag: str - """ - - _validation = { - "name": {"required": True}, - "format": {"required": True, "constant": True}, - "synonyms": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "format": {"key": "format", "type": "str"}, - "synonyms": {"key": "synonyms", "type": "str"}, - "encryption_key": {"key": "encryptionKey", "type": "SearchResourceEncryptionKey"}, - "e_tag": {"key": "@odata\\.etag", "type": "str"}, - } - - format = "solr" - - def __init__( - self, - *, - name: str, - synonyms: str, - encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, - e_tag: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the synonym map. Required. - :paramtype name: str - :keyword synonyms: A series of synonym rules in the specified synonym map format. The rules - must be separated by newlines. Required. - :paramtype synonyms: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data. Once you have - encrypted your data, it will always remain encrypted. The search service will ignore attempts - to set this property to null. You can change this property as needed if you want to rotate your - encryption key; Your data will be unaffected. Encryption with customer-managed keys is not - available for free search services, and is only available for paid services created on or after - January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword e_tag: The ETag of the synonym map. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.name = name - self.synonyms = synonyms - self.encryption_key = encryption_key - self.e_tag = e_tag - - -class SynonymTokenFilter(TokenFilter): - """Matches single or multi-word synonyms in a token stream. This token filter is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar synonyms: A list of synonyms in following one of two formats: 1. incredible, - unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced - with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma - separated list of equivalent words. Set the expand option to change how this list is - interpreted. Required. - :vartype synonyms: list[str] - :ivar ignore_case: A value indicating whether to case-fold input for matching. Default is - false. - :vartype ignore_case: bool - :ivar expand: A value indicating whether all words in the list of synonyms (if => notation is - not used) will map to one another. If true, all words in the list of synonyms (if => notation - is not used) will map to one another. The following list: incredible, unbelievable, fabulous, - amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, - unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, - fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => - incredible. Default is true. - :vartype expand: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "synonyms": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "synonyms": {"key": "synonyms", "type": "[str]"}, - "ignore_case": {"key": "ignoreCase", "type": "bool"}, - "expand": {"key": "expand", "type": "bool"}, - } - - def __init__( - self, *, name: str, synonyms: list[str], ignore_case: bool = False, expand: bool = True, **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword synonyms: A list of synonyms in following one of two formats: 1. incredible, - unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced - with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma - separated list of equivalent words. Set the expand option to change how this list is - interpreted. Required. - :paramtype synonyms: list[str] - :keyword ignore_case: A value indicating whether to case-fold input for matching. Default is - false. - :paramtype ignore_case: bool - :keyword expand: A value indicating whether all words in the list of synonyms (if => notation - is not used) will map to one another. If true, all words in the list of synonyms (if => - notation is not used) will map to one another. The following list: incredible, unbelievable, - fabulous, amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, - unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, - fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => - incredible. Default is true. - :paramtype expand: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.SynonymTokenFilter" - self.synonyms = synonyms - self.ignore_case = ignore_case - self.expand = expand - - -class TagScoringFunction(ScoringFunction): - """Defines a function that boosts scores of documents with string values matching a given list of - tags. - - All required parameters must be populated in order to send to server. - - :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, - distance, and tag. The function type must be lower case. Required. - :vartype type: str - :ivar field_name: The name of the field used as input to the scoring function. Required. - :vartype field_name: str - :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :vartype boost: float - :ivar interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :vartype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :ivar parameters: Parameter values for the tag scoring function. Required. - :vartype parameters: ~azure.search.documents.indexes.models.TagScoringParameters - """ - - _validation = { - "type": {"required": True}, - "field_name": {"required": True}, - "boost": {"required": True}, - "parameters": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "field_name": {"key": "fieldName", "type": "str"}, - "boost": {"key": "boost", "type": "float"}, - "interpolation": {"key": "interpolation", "type": "str"}, - "parameters": {"key": "tag", "type": "TagScoringParameters"}, - } - - def __init__( - self, - *, - field_name: str, - boost: float, - parameters: "_models.TagScoringParameters", - interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword field_name: The name of the field used as input to the scoring function. Required. - :paramtype field_name: str - :keyword boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. - Required. - :paramtype boost: float - :keyword interpolation: A value indicating how boosting will be interpolated across document - scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and - "logarithmic". - :paramtype interpolation: str or - ~azure.search.documents.indexes.models.ScoringFunctionInterpolation - :keyword parameters: Parameter values for the tag scoring function. Required. - :paramtype parameters: ~azure.search.documents.indexes.models.TagScoringParameters - """ - super().__init__(field_name=field_name, boost=boost, interpolation=interpolation, **kwargs) - self.type: str = "tag" - self.parameters = parameters - - -class TagScoringParameters(_serialization.Model): - """Provides parameter values to a tag scoring function. - - All required parameters must be populated in order to send to server. - - :ivar tags_parameter: The name of the parameter passed in search queries to specify the list of - tags to compare against the target field. Required. - :vartype tags_parameter: str - """ - - _validation = { - "tags_parameter": {"required": True}, - } - - _attribute_map = { - "tags_parameter": {"key": "tagsParameter", "type": "str"}, - } - - def __init__(self, *, tags_parameter: str, **kwargs: Any) -> None: - """ - :keyword tags_parameter: The name of the parameter passed in search queries to specify the list - of tags to compare against the target field. Required. - :paramtype tags_parameter: str - """ - super().__init__(**kwargs) - self.tags_parameter = tags_parameter - - -class TextTranslationSkill(SearchIndexerSkill): - """A skill to translate text from one language to another. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_to_language_code: The language code to translate documents into for documents - that don't specify the to language explicitly. Required. Known values are: "af", "ar", "bn", - "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", - "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :vartype default_to_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :ivar default_from_language_code: The language code to translate documents from for documents - that don't specify the from language explicitly. Known values are: "af", "ar", "bn", "bs", - "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", "fi", - "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :vartype default_from_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :ivar suggested_from: The language code to translate documents from when neither the - fromLanguageCode input nor the defaultFromLanguageCode parameter are provided, and the - automatic language detection is unsuccessful. Default is ``en``. Known values are: "af", "ar", - "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", - "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", - "tlh", "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", - "pt-br", "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", - "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and - "is". - :vartype suggested_from: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "default_to_language_code": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_to_language_code": {"key": "defaultToLanguageCode", "type": "str"}, - "default_from_language_code": {"key": "defaultFromLanguageCode", "type": "str"}, - "suggested_from": {"key": "suggestedFrom", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - default_to_language_code: Union[str, "_models.TextTranslationSkillLanguage"], - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - default_from_language_code: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, - suggested_from: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword default_to_language_code: The language code to translate documents into for documents - that don't specify the to language explicitly. Required. Known values are: "af", "ar", "bn", - "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", - "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :paramtype default_to_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :keyword default_from_language_code: The language code to translate documents from for - documents that don't specify the from language explicitly. Known values are: "af", "ar", "bn", - "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", - "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", - "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", - "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", - "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and "is". - :paramtype default_from_language_code: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - :keyword suggested_from: The language code to translate documents from when neither the - fromLanguageCode input nor the defaultFromLanguageCode parameter are provided, and the - automatic language detection is unsuccessful. Default is ``en``. Known values are: "af", "ar", - "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", - "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", - "tlh", "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", - "pt-br", "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", - "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", "pa", and - "is". - :paramtype suggested_from: str or - ~azure.search.documents.indexes.models.TextTranslationSkillLanguage - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Text.TranslationSkill" - self.default_to_language_code = default_to_language_code - self.default_from_language_code = default_from_language_code - self.suggested_from = suggested_from - - -class TextWeights(_serialization.Model): - """Defines weights on index fields for which matches should boost scoring in search queries. - - All required parameters must be populated in order to send to server. - - :ivar weights: The dictionary of per-field weights to boost document scoring. The keys are - field names and the values are the weights for each field. Required. - :vartype weights: dict[str, float] - """ - - _validation = { - "weights": {"required": True}, - } - - _attribute_map = { - "weights": {"key": "weights", "type": "{float}"}, - } - - def __init__(self, *, weights: dict[str, float], **kwargs: Any) -> None: - """ - :keyword weights: The dictionary of per-field weights to boost document scoring. The keys are - field names and the values are the weights for each field. Required. - :paramtype weights: dict[str, float] - """ - super().__init__(**kwargs) - self.weights = weights - - -class TruncateTokenFilter(TokenFilter): - """Truncates the terms to a specific length. This token filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar length: The length at which terms will be truncated. Default and maximum is 300. - :vartype length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "length": {"key": "length", "type": "int"}, - } - - def __init__(self, *, name: str, length: int = 300, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword length: The length at which terms will be truncated. Default and maximum is 300. - :paramtype length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.TruncateTokenFilter" - self.length = length - - -class UaxUrlEmailTokenizer(LexicalTokenizer): - """Tokenizes urls and emails as one token. This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. - :vartype odata_type: str - :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or - underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :vartype max_token_length: int - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - "max_token_length": {"maximum": 300}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "max_token_length": {"key": "maxTokenLength", "type": "int"}, - } - - def __init__(self, *, name: str, max_token_length: int = 255, **kwargs: Any) -> None: - """ - :keyword name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :paramtype name: str - :keyword max_token_length: The maximum token length. Default is 255. Tokens longer than the - maximum length are split. The maximum token length that can be used is 300 characters. - :paramtype max_token_length: int - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer" - self.max_token_length = max_token_length - - -class UniqueTokenFilter(TokenFilter): - """Filters out tokens with same text as the previous token. This token filter is implemented using - Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar only_on_same_position: A value indicating whether to remove duplicates only at the same - position. Default is false. - :vartype only_on_same_position: bool - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "only_on_same_position": {"key": "onlyOnSamePosition", "type": "bool"}, - } - - def __init__(self, *, name: str, only_on_same_position: bool = False, **kwargs: Any) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword only_on_same_position: A value indicating whether to remove duplicates only at the - same position. Default is false. - :paramtype only_on_same_position: bool - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.UniqueTokenFilter" - self.only_on_same_position = only_on_same_position - - -class VectorSearch(_serialization.Model): - """Contains configuration options related to vector search. - - :ivar profiles: Defines combinations of configurations to use with vector search. - :vartype profiles: list[~azure.search.documents.indexes.models.VectorSearchProfile] - :ivar algorithms: Contains configuration options specific to the algorithm used during indexing - or querying. - :vartype algorithms: - list[~azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration] - :ivar vectorizers: Contains configuration options on how to vectorize text vector queries. - :vartype vectorizers: list[~azure.search.documents.indexes.models.VectorSearchVectorizer] - :ivar compressions: Contains configuration options specific to the compression method used - during indexing or querying. - :vartype compressions: list[~azure.search.documents.indexes.models.VectorSearchCompression] - """ - - _attribute_map = { - "profiles": {"key": "profiles", "type": "[VectorSearchProfile]"}, - "algorithms": {"key": "algorithms", "type": "[VectorSearchAlgorithmConfiguration]"}, - "vectorizers": {"key": "vectorizers", "type": "[VectorSearchVectorizer]"}, - "compressions": {"key": "compressions", "type": "[VectorSearchCompression]"}, - } - - def __init__( - self, - *, - profiles: Optional[list["_models.VectorSearchProfile"]] = None, - algorithms: Optional[list["_models.VectorSearchAlgorithmConfiguration"]] = None, - vectorizers: Optional[list["_models.VectorSearchVectorizer"]] = None, - compressions: Optional[list["_models.VectorSearchCompression"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword profiles: Defines combinations of configurations to use with vector search. - :paramtype profiles: list[~azure.search.documents.indexes.models.VectorSearchProfile] - :keyword algorithms: Contains configuration options specific to the algorithm used during - indexing or querying. - :paramtype algorithms: - list[~azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration] - :keyword vectorizers: Contains configuration options on how to vectorize text vector queries. - :paramtype vectorizers: list[~azure.search.documents.indexes.models.VectorSearchVectorizer] - :keyword compressions: Contains configuration options specific to the compression method used - during indexing or querying. - :paramtype compressions: list[~azure.search.documents.indexes.models.VectorSearchCompression] - """ - super().__init__(**kwargs) - self.profiles = profiles - self.algorithms = algorithms - self.vectorizers = vectorizers - self.compressions = compressions - - -class VectorSearchProfile(_serialization.Model): - """Defines a combination of configurations to use with vector search. - - All required parameters must be populated in order to send to server. - - :ivar name: The name to associate with this particular vector search profile. Required. - :vartype name: str - :ivar algorithm_configuration_name: The name of the vector search algorithm configuration that - specifies the algorithm and optional parameters. Required. - :vartype algorithm_configuration_name: str - :ivar vectorizer_name: The name of the vectorization being configured for use with vector - search. - :vartype vectorizer_name: str - :ivar compression_name: The name of the compression method configuration that specifies the - compression method and optional parameters. - :vartype compression_name: str - """ - - _validation = { - "name": {"required": True}, - "algorithm_configuration_name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "algorithm_configuration_name": {"key": "algorithm", "type": "str"}, - "vectorizer_name": {"key": "vectorizer", "type": "str"}, - "compression_name": {"key": "compression", "type": "str"}, - } - - def __init__( - self, - *, - name: str, - algorithm_configuration_name: str, - vectorizer_name: Optional[str] = None, - compression_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name to associate with this particular vector search profile. Required. - :paramtype name: str - :keyword algorithm_configuration_name: The name of the vector search algorithm configuration - that specifies the algorithm and optional parameters. Required. - :paramtype algorithm_configuration_name: str - :keyword vectorizer_name: The name of the vectorization being configured for use with vector - search. - :paramtype vectorizer_name: str - :keyword compression_name: The name of the compression method configuration that specifies the - compression method and optional parameters. - :paramtype compression_name: str - """ - super().__init__(**kwargs) - self.name = name - self.algorithm_configuration_name = algorithm_configuration_name - self.vectorizer_name = vectorizer_name - self.compression_name = compression_name - - -class VisionVectorizeSkill(SearchIndexerSkill): - """Allows you to generate a vector embedding for a given image or text input using the Azure AI - Services Vision Vectorize API. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of skill. Required. - :vartype odata_type: str - :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :vartype name: str - :ivar description: The description of the skill which describes the inputs, outputs, and usage - of the skill. - :vartype description: str - :ivar context: Represents the level at which operations take place, such as the document root - or document content (for example, /document or /document/content). The default is /document. - :vartype context: str - :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of - an upstream skill. Required. - :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: The output of a skill is either a field in a search index, or a value that can - be consumed as an input by another skill. Required. - :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :vartype model_version: str - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "model_version": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "model_version": {"key": "modelVersion", "type": "str"}, - } - - def __init__( - self, - *, - inputs: list["_models.InputFieldMappingEntry"], - outputs: list["_models.OutputFieldMappingEntry"], - model_version: str, - name: Optional[str] = None, - description: Optional[str] = None, - context: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the skill which uniquely identifies it within the skillset. A skill - with no name defined will be given a default name of its 1-based index in the skills array, - prefixed with the character '#'. - :paramtype name: str - :keyword description: The description of the skill which describes the inputs, outputs, and - usage of the skill. - :paramtype description: str - :keyword context: Represents the level at which operations take place, such as the document - root or document content (for example, /document or /document/content). The default is - /document. - :paramtype context: str - :keyword inputs: Inputs of the skills could be a column in the source data set, or the output - of an upstream skill. Required. - :paramtype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :keyword outputs: The output of a skill is either a field in a search index, or a value that - can be consumed as an input by another skill. Required. - :paramtype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :keyword model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. - :paramtype model_version: str - """ - super().__init__(name=name, description=description, context=context, inputs=inputs, outputs=outputs, **kwargs) - self.odata_type: str = "#Microsoft.Skills.Vision.VectorizeSkill" - self.model_version = model_version - - -class WebApiVectorizer(VectorSearchVectorizer): - """Specifies a user-defined vectorizer for generating the vector embedding of a query string. - Integration of an external vectorizer is achieved using the custom Web API interface of a - skillset. - - All required parameters must be populated in order to send to server. - - :ivar vectorizer_name: The name to associate with this particular vectorization method. - Required. - :vartype vectorizer_name: str - :ivar kind: The name of the kind of vectorization method being configured for use with vector - search. Required. Known values are: "azureOpenAI", "customWebApi", "aiServicesVision", and - "aml". - :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind - :ivar web_api_parameters: Specifies the properties of the user-defined vectorizer. - :vartype web_api_parameters: ~azure.search.documents.indexes.models.WebApiVectorizerParameters - """ - - _validation = { - "vectorizer_name": {"required": True}, - "kind": {"required": True}, - } - - _attribute_map = { - "vectorizer_name": {"key": "name", "type": "str"}, - "kind": {"key": "kind", "type": "str"}, - "web_api_parameters": {"key": "customWebApiParameters", "type": "WebApiVectorizerParameters"}, - } - - def __init__( - self, - *, - vectorizer_name: str, - web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = None, - **kwargs: Any - ) -> None: - """ - :keyword vectorizer_name: The name to associate with this particular vectorization method. - Required. - :paramtype vectorizer_name: str - :keyword web_api_parameters: Specifies the properties of the user-defined vectorizer. - :paramtype web_api_parameters: - ~azure.search.documents.indexes.models.WebApiVectorizerParameters - """ - super().__init__(vectorizer_name=vectorizer_name, **kwargs) - self.kind: str = "customWebApi" - self.web_api_parameters = web_api_parameters - - -class WebApiVectorizerParameters(_serialization.Model): - """Specifies the properties for connecting to a user-defined vectorizer. - - :ivar url: The URI of the Web API providing the vectorizer. - :vartype url: str - :ivar http_headers: The headers required to make the HTTP request. - :vartype http_headers: dict[str, str] - :ivar http_method: The method for the HTTP request. - :vartype http_method: str - :ivar timeout: The desired timeout for the request. Default is 30 seconds. - :vartype timeout: ~datetime.timedelta - :ivar auth_resource_id: Applies to custom endpoints that connect to external code in an Azure - function or some other application that provides the transformations. This value should be the - application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the vectorization connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - - _attribute_map = { - "url": {"key": "uri", "type": "str"}, - "http_headers": {"key": "httpHeaders", "type": "{str}"}, - "http_method": {"key": "httpMethod", "type": "str"}, - "timeout": {"key": "timeout", "type": "duration"}, - "auth_resource_id": {"key": "authResourceId", "type": "str"}, - "auth_identity": {"key": "authIdentity", "type": "SearchIndexerDataIdentity"}, - } - - def __init__( - self, - *, - url: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, - http_method: Optional[str] = None, - timeout: Optional[datetime.timedelta] = None, - auth_resource_id: Optional[str] = None, - auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword url: The URI of the Web API providing the vectorizer. - :paramtype url: str - :keyword http_headers: The headers required to make the HTTP request. - :paramtype http_headers: dict[str, str] - :keyword http_method: The method for the HTTP request. - :paramtype http_method: str - :keyword timeout: The desired timeout for the request. Default is 30 seconds. - :paramtype timeout: ~datetime.timedelta - :keyword auth_resource_id: Applies to custom endpoints that connect to external code in an - Azure function or some other application that provides the transformations. This value should - be the application ID created for the function or app when it was registered with Azure Active - Directory. When specified, the vectorization connects to the function or app using a managed ID - (either system or user-assigned) of the search service and the access token of the function or - app, using this value as the resource id for creating the scope of the access token. - :paramtype auth_resource_id: str - :keyword auth_identity: The user-assigned managed identity used for outbound connections. If an - authResourceId is provided and it's not specified, the system-assigned managed identity is - used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. - If set to "none", the value of this property is cleared. - :paramtype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - """ - super().__init__(**kwargs) - self.url = url - self.http_headers = http_headers - self.http_method = http_method - self.timeout = timeout - self.auth_resource_id = auth_resource_id - self.auth_identity = auth_identity - - -class WordDelimiterTokenFilter(TokenFilter): - """Splits words into subwords and performs optional transformations on subword groups. This token - filter is implemented using Apache Lucene. - - All required parameters must be populated in order to send to server. - - :ivar odata_type: A URI fragment specifying the type of token filter. Required. - :vartype odata_type: str - :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes - or underscores, can only start and end with alphanumeric characters, and is limited to 128 - characters. Required. - :vartype name: str - :ivar generate_word_parts: A value indicating whether to generate part words. If set, causes - parts of words to be generated; for example "AzureSearch" becomes "Azure" "Search". Default is - true. - :vartype generate_word_parts: bool - :ivar generate_number_parts: A value indicating whether to generate number subwords. Default is - true. - :vartype generate_number_parts: bool - :ivar catenate_words: A value indicating whether maximum runs of word parts will be catenated. - For example, if this is set to true, "Azure-Search" becomes "AzureSearch". Default is false. - :vartype catenate_words: bool - :ivar catenate_numbers: A value indicating whether maximum runs of number parts will be - catenated. For example, if this is set to true, "1-2" becomes "12". Default is false. - :vartype catenate_numbers: bool - :ivar catenate_all: A value indicating whether all subword parts will be catenated. For - example, if this is set to true, "Azure-Search-1" becomes "AzureSearch1". Default is false. - :vartype catenate_all: bool - :ivar split_on_case_change: A value indicating whether to split words on caseChange. For - example, if this is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. - :vartype split_on_case_change: bool - :ivar preserve_original: A value indicating whether original words will be preserved and added - to the subword list. Default is false. - :vartype preserve_original: bool - :ivar split_on_numerics: A value indicating whether to split on numbers. For example, if this - is set to true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. - :vartype split_on_numerics: bool - :ivar stem_english_possessive: A value indicating whether to remove trailing "'s" for each - subword. Default is true. - :vartype stem_english_possessive: bool - :ivar protected_words: A list of tokens to protect from being delimited. - :vartype protected_words: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - "name": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "generate_word_parts": {"key": "generateWordParts", "type": "bool"}, - "generate_number_parts": {"key": "generateNumberParts", "type": "bool"}, - "catenate_words": {"key": "catenateWords", "type": "bool"}, - "catenate_numbers": {"key": "catenateNumbers", "type": "bool"}, - "catenate_all": {"key": "catenateAll", "type": "bool"}, - "split_on_case_change": {"key": "splitOnCaseChange", "type": "bool"}, - "preserve_original": {"key": "preserveOriginal", "type": "bool"}, - "split_on_numerics": {"key": "splitOnNumerics", "type": "bool"}, - "stem_english_possessive": {"key": "stemEnglishPossessive", "type": "bool"}, - "protected_words": {"key": "protectedWords", "type": "[str]"}, - } - - def __init__( - self, - *, - name: str, - generate_word_parts: bool = True, - generate_number_parts: bool = True, - catenate_words: bool = False, - catenate_numbers: bool = False, - catenate_all: bool = False, - split_on_case_change: bool = True, - preserve_original: bool = False, - split_on_numerics: bool = True, - stem_english_possessive: bool = True, - protected_words: Optional[list[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the token filter. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. Required. - :paramtype name: str - :keyword generate_word_parts: A value indicating whether to generate part words. If set, causes - parts of words to be generated; for example "AzureSearch" becomes "Azure" "Search". Default is - true. - :paramtype generate_word_parts: bool - :keyword generate_number_parts: A value indicating whether to generate number subwords. Default - is true. - :paramtype generate_number_parts: bool - :keyword catenate_words: A value indicating whether maximum runs of word parts will be - catenated. For example, if this is set to true, "Azure-Search" becomes "AzureSearch". Default - is false. - :paramtype catenate_words: bool - :keyword catenate_numbers: A value indicating whether maximum runs of number parts will be - catenated. For example, if this is set to true, "1-2" becomes "12". Default is false. - :paramtype catenate_numbers: bool - :keyword catenate_all: A value indicating whether all subword parts will be catenated. For - example, if this is set to true, "Azure-Search-1" becomes "AzureSearch1". Default is false. - :paramtype catenate_all: bool - :keyword split_on_case_change: A value indicating whether to split words on caseChange. For - example, if this is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. - :paramtype split_on_case_change: bool - :keyword preserve_original: A value indicating whether original words will be preserved and - added to the subword list. Default is false. - :paramtype preserve_original: bool - :keyword split_on_numerics: A value indicating whether to split on numbers. For example, if - this is set to true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. - :paramtype split_on_numerics: bool - :keyword stem_english_possessive: A value indicating whether to remove trailing "'s" for each - subword. Default is true. - :paramtype stem_english_possessive: bool - :keyword protected_words: A list of tokens to protect from being delimited. - :paramtype protected_words: list[str] - """ - super().__init__(name=name, **kwargs) - self.odata_type: str = "#Microsoft.Azure.Search.WordDelimiterTokenFilter" - self.generate_word_parts = generate_word_parts - self.generate_number_parts = generate_number_parts - self.catenate_words = catenate_words - self.catenate_numbers = catenate_numbers - self.catenate_all = catenate_all - self.split_on_case_change = split_on_case_change - self.preserve_original = preserve_original - self.split_on_numerics = split_on_numerics - self.stem_english_possessive = stem_english_possessive - self.protected_words = protected_words diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py deleted file mode 100644 index ff48959532fe..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._knowledge_agents_operations import KnowledgeAgentsOperations # type: ignore -from ._knowledge_sources_operations import KnowledgeSourcesOperations # type: ignore -from ._data_sources_operations import DataSourcesOperations # type: ignore -from ._indexers_operations import IndexersOperations # type: ignore -from ._skillsets_operations import SkillsetsOperations # type: ignore -from ._synonym_maps_operations import SynonymMapsOperations # type: ignore -from ._indexes_operations import IndexesOperations # type: ignore -from ._aliases_operations import AliasesOperations # type: ignore -from ._search_service_client_operations import _SearchServiceClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeAgentsOperations", - "KnowledgeSourcesOperations", - "DataSourcesOperations", - "IndexersOperations", - "SkillsetsOperations", - "SynonymMapsOperations", - "IndexesOperations", - "AliasesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py deleted file mode 100644 index a174ad9aa35b..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_aliases_operations.py +++ /dev/null @@ -1,755 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - alias_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases('{aliasName}')") - path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - alias_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases('{aliasName}')") - path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(alias_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/aliases('{aliasName}')") - path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class AliasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`aliases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create( - self, - alias: _models.SearchAlias, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - alias: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Required. - :type alias: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - alias: Union[_models.SearchAlias, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Alias - - :param alias: The definition of the alias to create. Is either a SearchAlias type or a - IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.SearchAlias"]: - """Lists all aliases available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Aliases - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchAlias or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListAliasesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListAliasesResult", pipeline_response) - list_of_elem = deserialized.aliases - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: _models.SearchAlias, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - alias_name: str, - prefer: Union[str, _models.Enum0], - alias: Union[_models.SearchAlias, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Alias - - :param alias_name: The definition of the alias to create or update. Required. - :type alias_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param alias: The definition of the alias to create or update. Is either a SearchAlias type or - a IO[bytes] type. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias - else: - _json = self._serialize.body(alias, "SearchAlias") - - _request = build_create_or_update_request( - alias_name=alias_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - alias_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Alias - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, alias_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchAlias: - """Retrieves an alias definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Alias - - :param alias_name: The name of the alias to retrieve. Required. - :type alias_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchAlias or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchAlias] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - alias_name=alias_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchAlias", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py deleted file mode 100644 index ccfcee79d175..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_data_sources_operations.py +++ /dev/null @@ -1,749 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - data_source_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources('{dataSourceName}')") - path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - data_source_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources('{dataSourceName}')") - path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - data_source_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources('{dataSourceName}')") - path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/datasources") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class DataSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`data_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: _models.SearchIndexerDataSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - data_source_name: str, - prefer: Union[str, _models.Enum0], - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Data-Source - - :param data_source_name: The name of the datasource to create or update. Required. - :type data_source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param data_source: The definition of the datasource to create or update. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_or_update_request( - data_source_name=data_source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - data_source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Data-Source - - :param data_source_name: The name of the datasource to delete. Required. - :type data_source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, data_source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Retrieves a datasource definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Data-Source - - :param data_source_name: The name of the datasource to retrieve. Required. - :type data_source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - data_source_name=data_source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListDataSourcesResult: - """Lists all datasources available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Data-Sources - - :param select: Selects which top-level properties of the data sources to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListDataSourcesResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListDataSourcesResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListDataSourcesResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - data_source: _models.SearchIndexerDataSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - data_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Required. - :type data_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - data_source: Union[_models.SearchIndexerDataSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerDataSource: - """Creates a new datasource. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Data-Source - - :param data_source: The definition of the datasource to create. Is either a - SearchIndexerDataSource type or a IO[bytes] type. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerDataSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerDataSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source - else: - _json = self._serialize.body(data_source, "SearchIndexerDataSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerDataSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py deleted file mode 100644 index 1cf75a9c4b9b..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexers_operations.py +++ /dev/null @@ -1,1394 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_reset_request( - indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.reset") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_reset_docs_request( - indexer_name: str, *, overwrite: bool = False, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.resetdocs") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if overwrite is not None: - _params["overwrite"] = _SERIALIZER.query("overwrite", overwrite, "bool") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resync_request( - indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.resync") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_run_request(indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.run") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - indexer_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - if disable_cache_reprocessing_change_detection is not None: - _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( - "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" - ) - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - indexer_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_status_request( - indexer_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexers('{indexerName}')/search.status") - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class IndexersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`indexers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def reset( # pylint: disable=inconsistent-return-statements - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Resets the change tracking state associated with an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Reset-Indexer - - :param indexer_name: The name of the indexer to reset. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_reset_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[_models.DocumentKeysOrIds] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def reset_docs( - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Default value is None. - :type keys_or_ids: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def reset_docs( # pylint: disable=inconsistent-return-statements - self, - indexer_name: str, - overwrite: bool = False, - request_options: Optional[_models.RequestOptions] = None, - keys_or_ids: Optional[Union[_models.DocumentKeysOrIds, IO[bytes]]] = None, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - .. seealso:: - - https://aka.ms/reset-documents - - :param indexer_name: The name of the indexer to reset documents for. Required. - :type indexer_name: str - :param overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is False. - :type overwrite: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :param keys_or_ids: Is either a DocumentKeysOrIds type or a IO[bytes] type. Default value is - None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if keys_or_ids else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" if keys_or_ids else None - _json = None - _content = None - if isinstance(keys_or_ids, (IOBase, bytes)): - _content = keys_or_ids - else: - if keys_or_ids is not None: - _json = self._serialize.body(keys_or_ids, "DocumentKeysOrIds") - else: - _json = None - - _request = build_reset_docs_request( - indexer_name=indexer_name, - overwrite=overwrite, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def resync( - self, - indexer_name: str, - indexer_resync: _models.IndexerResyncBody, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def resync( - self, - indexer_name: str, - indexer_resync: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Required. - :type indexer_resync: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def resync( # pylint: disable=inconsistent-return-statements - self, - indexer_name: str, - indexer_resync: Union[_models.IndexerResyncBody, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Resync-Indexer - - :param indexer_name: The name of the indexer to resync for. Required. - :type indexer_name: str - :param indexer_resync: Is either a IndexerResyncBody type or a IO[bytes] type. Required. - :type indexer_resync: ~azure.search.documents.indexes.models.IndexerResyncBody or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer_resync, (IOBase, bytes)): - _content = indexer_resync - else: - _json = self._serialize.body(indexer_resync, "IndexerResyncBody") - - _request = build_resync_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def run( # pylint: disable=inconsistent-return-statements - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> None: - """Runs an indexer on-demand. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Run-Indexer - - :param indexer_name: The name of the indexer to run. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_run_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: _models.SearchIndexer, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - indexer_name: str, - prefer: Union[str, _models.Enum0], - indexer: Union[_models.SearchIndexer, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer_name: The name of the indexer to create or update. Required. - :type indexer_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param indexer: The definition of the indexer to create or update. Is either a SearchIndexer - type or a IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_or_update_request( - indexer_name=indexer_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - indexer_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Indexer - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexer: - """Retrieves an indexer definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer - - :param indexer_name: The name of the indexer to retrieve. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListIndexersResult: - """Lists all indexers available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexers - - :param select: Selects which top-level properties of the indexers to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListIndexersResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexersResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListIndexersResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - indexer: _models.SearchIndexer, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - indexer: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Required. - :type indexer: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - indexer: Union[_models.SearchIndexer, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexer: - """Creates a new indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Indexer - - :param indexer: The definition of the indexer to create. Is either a SearchIndexer type or a - IO[bytes] type. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexer or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexer] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _json = self._serialize.body(indexer, "SearchIndexer") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexer", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_status( - self, indexer_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerStatus: - """Returns the current status and execution history of an indexer. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Indexer-Status - - :param indexer_name: The name of the indexer for which to retrieve status. Required. - :type indexer_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerStatus or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerStatus] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_status_request( - indexer_name=indexer_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py deleted file mode 100644 index 31eb1e38c0b5..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_indexes_operations.py +++ /dev/null @@ -1,1058 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - index_name: str, - *, - prefer: Union[str, _models.Enum0], - allow_index_downtime: Optional[bool] = None, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if allow_index_downtime is not None: - _params["allowIndexDowntime"] = _SERIALIZER.query("allow_index_downtime", allow_index_downtime, "bool") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - index_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(index_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_statistics_request( - index_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')/search.stats") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_analyze_request( - index_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexes('{indexName}')/search.analyze") - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`indexes` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create( - self, - index: _models.SearchIndex, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - index: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Required. - :type index: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - index: Union[_models.SearchIndex, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Index - - :param index: The definition of the index to create. Is either a SearchIndex type or a - IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.SearchIndex"]: - """Lists all indexes available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Indexes - - :param select: Selects which top-level properties of the index definitions to retrieve. - Specified as a comma-separated list of JSON property names, or '*' for all properties. The - default is all properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either SearchIndex or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexesResult", pipeline_response) - list_of_elem = deserialized.indexes - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: _models.SearchIndex, - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: IO[bytes], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - index_name: str, - prefer: Union[str, _models.Enum0], - index: Union[_models.SearchIndex, IO[bytes]], - allow_index_downtime: Optional[bool] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Index - - :param index_name: The definition of the index to create or update. Required. - :type index_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param index: The definition of the index to create or update. Is either a SearchIndex type or - a IO[bytes] type. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or IO[bytes] - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :type allow_index_downtime: bool - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _json = self._serialize.body(index, "SearchIndex") - - _request = build_create_or_update_request( - index_name=index_name, - prefer=prefer, - allow_index_downtime=allow_index_downtime, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - index_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. This operation is permanent, with no - recovery option. Make sure you have a master copy of your index definition, data ingestion - code, and a backup of the primary data source in case you need to re-build the index. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Index - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndex: - """Retrieves an index definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index - - :param index_name: The name of the index to retrieve. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndex or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndex] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndex", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_statistics( - self, index_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.GetIndexStatisticsResult: - """Returns statistics for the given index, including a document count and storage usage. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Index-Statistics - - :param index_name: The name of the index for which to retrieve statistics. Required. - :type index_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: GetIndexStatisticsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GetIndexStatisticsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_statistics_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("GetIndexStatisticsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def analyze( - self, - index_name: str, - request: _models.AnalyzeRequest, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def analyze( - self, - index_name: str, - request: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def analyze( - self, - index_name: str, - request: Union[_models.AnalyzeRequest, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/test-analyzer - - :param index_name: The name of the index for which to test an analyzer. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Is either a - AnalyzeRequest type or a IO[bytes] type. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: AnalyzeResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AnalyzeResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(request, (IOBase, bytes)): - _content = request - else: - _json = self._serialize.body(request, "AnalyzeRequest") - - _request = build_analyze_request( - index_name=index_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("AnalyzeResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_agents_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_agents_operations.py deleted file mode 100644 index 9bdca072bfa6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_agents_operations.py +++ /dev/null @@ -1,727 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - agent_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/agents('{agentName}')") - path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - agent_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/agents('{agentName}')") - path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(agent_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/agents('{agentName}')") - path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/agents") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/agents") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class KnowledgeAgentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`knowledge_agents` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - agent_name: str, - prefer: Union[str, _models.Enum0], - knowledge_agent: _models.KnowledgeAgent, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent to create or update. Required. - :type agent_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - agent_name: str, - prefer: Union[str, _models.Enum0], - knowledge_agent: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent to create or update. Required. - :type agent_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - agent_name: str, - prefer: Union[str, _models.Enum0], - knowledge_agent: Union[_models.KnowledgeAgent, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent to create or update. Required. - :type agent_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_agent: The definition of the agent to create or update. Is either a - KnowledgeAgent type or a IO[bytes] type. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeAgent] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent - else: - _json = self._serialize.body(knowledge_agent, "KnowledgeAgent") - - _request = build_create_or_update_request( - agent_name=agent_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgent", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - agent_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing agent. - - :param agent_name: The name of the agent to delete. Required. - :type agent_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - agent_name=agent_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, agent_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeAgent: - """Retrieves an agent definition. - - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeAgent] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - agent_name=agent_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgent", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.KnowledgeAgent"]: - """Lists all agents available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeAgent or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeAgentsResult", pipeline_response) - list_of_elem = deserialized.knowledge_agents - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create( - self, - knowledge_agent: _models.KnowledgeAgent, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - knowledge_agent: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - knowledge_agent: Union[_models.KnowledgeAgent, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Is either a KnowledgeAgent type - or a IO[bytes] type. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeAgent or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeAgent] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent - else: - _json = self._serialize.body(knowledge_agent, "KnowledgeAgent") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeAgent", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py deleted file mode 100644 index 606c4d50e437..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_knowledge_sources_operations.py +++ /dev/null @@ -1,727 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - source_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - source_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(source_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources('{sourceName}')") - path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/knowledgesources") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class KnowledgeSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`knowledge_sources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: _models.KnowledgeSource, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - source_name: str, - prefer: Union[str, _models.Enum0], - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source to create or update. Required. - :type source_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param knowledge_source: The definition of the knowledge source to create or update. Is either - a KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_or_update_request( - source_name=source_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - source_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, source_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.KnowledgeSource: - """Retrieves a knowledge source definition. - - :param source_name: The name of the knowledge source to retrieve. Required. - :type source_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - source_name=source_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.KnowledgeSource"]: - """Lists all knowledge sources available for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either KnowledgeSource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListKnowledgeSourcesResult", pipeline_response) - list_of_elem = deserialized.knowledge_sources - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @overload - def create( - self, - knowledge_source: _models.KnowledgeSource, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - knowledge_source: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - knowledge_source: Union[_models.KnowledgeSource, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The definition of the knowledge source to create. Is either a - KnowledgeSource type or a IO[bytes] type. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: KnowledgeSource or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeSource] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source - else: - _json = self._serialize.body(knowledge_source, "KnowledgeSource") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("KnowledgeSource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py deleted file mode 100644 index 55b5dc6364ec..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_search_service_client_operations.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar -import urllib.parse - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_service_statistics_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/servicestats") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_index_stats_summary_request( - *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/indexstats") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class _SearchServiceClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchServiceClientConfiguration] -): - - @distributed_trace - def get_service_statistics( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchServiceStatistics: - """Gets service level statistics for a search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchServiceStatistics or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchServiceStatistics] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_service_statistics_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchServiceStatistics", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_index_stats_summary( - self, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> ItemPaged["_models.IndexStatisticsSummary"]: - """Retrieves a summary of statistics for all indexes in the search service. - - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: An iterator like instance of either IndexStatisticsSummary or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListIndexStatsSummary] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_index_stats_summary_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListIndexStatsSummary", pipeline_response) - list_of_elem = deserialized.indexes_statistics - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py deleted file mode 100644 index 460e2c091eee..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_skillsets_operations.py +++ /dev/null @@ -1,940 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - skillset_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - if disable_cache_reprocessing_change_detection is not None: - _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( - "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" - ) - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - skillset_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - skillset_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_reset_skills_request( - skillset_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/skillsets('{skillsetName}')/search.resetskills") - path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class SkillsetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`skillsets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: _models.SearchIndexerSkillset, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - skillset_name: str, - prefer: Union[str, _models.Enum0], - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/update-skillset - - :param skillset_name: The name of the skillset to create or update. Required. - :type skillset_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param skillset: The skillset containing one or more skills to create or update in a search - service. Is either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :type skip_indexer_reset_requirement_for_cache: bool - :param disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :type disable_cache_reprocessing_change_detection: bool - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_or_update_request( - skillset_name=skillset_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - skillset_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/delete-skillset - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, skillset_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Retrieves a skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/get-skillset - - :param skillset_name: The name of the skillset to retrieve. Required. - :type skillset_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSkillsetsResult: - """List all skillsets in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/list-skillset - - :param select: Selects which top-level properties of the skillsets to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSkillsetsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSkillsetsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSkillsetsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - skillset: _models.SearchIndexerSkillset, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - skillset: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - skillset: Union[_models.SearchIndexerSkillset, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/create-skillset - - :param skillset: The skillset containing one or more skills to create in a search service. Is - either a SearchIndexerSkillset type or a IO[bytes] type. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SearchIndexerSkillset or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _json = self._serialize.body(skillset, "SearchIndexerSkillset") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SearchIndexerSkillset", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def reset_skills( - self, - skillset_name: str, - skill_names: _models.SkillNames, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def reset_skills( - self, - skillset_name: str, - skill_names: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Required. - :type skill_names: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def reset_skills( # pylint: disable=inconsistent-return-statements - self, - skillset_name: str, - skill_names: Union[_models.SkillNames, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. - - .. seealso:: - - https://aka.ms/reset-skills - - :param skillset_name: The name of the skillset to reset. Required. - :type skillset_name: str - :param skill_names: The names of skills to reset. Is either a SkillNames type or a IO[bytes] - type. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(skill_names, (IOBase, bytes)): - _content = skill_names - else: - _json = self._serialize.body(skill_names, "SkillNames") - - _request = build_reset_skills_request( - skillset_name=skillset_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py deleted file mode 100644 index 556ba4b9ac58..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_synonym_maps_operations.py +++ /dev/null @@ -1,731 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import SearchServiceClientConfiguration -from .._utils.serialization import Deserializer, Serializer - -List = list -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_or_update_request( - synonym_map_name: str, - *, - prefer: Union[str, _models.Enum0], - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps('{synonymMapName}')") - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - synonym_map_name: str, - *, - x_ms_client_request_id: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps('{synonymMapName}')") - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - synonym_map_name: str, *, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps('{synonymMapName}')") - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - *, select: Optional[str] = None, x_ms_client_request_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps") - - # Construct parameters - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(*, x_ms_client_request_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/synonymmaps") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_client_request_id is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class SynonymMapsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.indexes.SearchServiceClient`'s - :attr:`synonym_maps` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: _models.SynonymMap, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - synonym_map_name: str, - prefer: Union[str, _models.Enum0], - synonym_map: Union[_models.SynonymMap, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Update-Synonym-Map - - :param synonym_map_name: The name of the synonym map to create or update. Required. - :type synonym_map_name: str - :param prefer: For HTTP PUT requests, instructs the service to return the created/updated - resource on success. "return=representation" Required. - :type prefer: str or ~azure.search.documents.indexes.models.Enum0 - :param synonym_map: The definition of the synonym map to create or update. Is either a - SynonymMap type or a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_or_update_request( - synonym_map_name=synonym_map_name, - prefer=prefer, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - synonym_map_name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> None: - """Deletes a synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Delete-Synonym-Map - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :param if_match: Defines the If-Match condition. The operation will be performed only if the - ETag on the server matches this value. Default value is None. - :type if_match: str - :param if_none_match: Defines the If-None-Match condition. The operation will be performed only - if the ETag on the server does not match this value. Default value is None. - :type if_none_match: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_delete_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - if_match=if_match, - if_none_match=if_none_match, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, synonym_map_name: str, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.SynonymMap: - """Retrieves a synonym map definition. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Get-Synonym-Map - - :param synonym_map_name: The name of the synonym map to retrieve. Required. - :type synonym_map_name: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_get_request( - synonym_map_name=synonym_map_name, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, select: Optional[str] = None, request_options: Optional[_models.RequestOptions] = None, **kwargs: Any - ) -> _models.ListSynonymMapsResult: - """Lists all synonym maps available for a search service. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/List-Synonym-Maps - - :param select: Selects which top-level properties of the synonym maps to retrieve. Specified as - a comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. Default value is None. - :type select: str - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: ListSynonymMapsResult or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListSynonymMapsResult] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - - _request = build_list_request( - select=select, - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("ListSynonymMapsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, - synonym_map: _models.SynonymMap, - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - synonym_map: IO[bytes], - request_options: Optional[_models.RequestOptions] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - synonym_map: Union[_models.SynonymMap, IO[bytes]], - request_options: Optional[_models.RequestOptions] = None, - **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map. - - .. seealso:: - - https://learn.microsoft.com/rest/api/searchservice/Create-Synonym-Map - - :param synonym_map: The definition of the synonym map to create. Is either a SynonymMap type or - a IO[bytes] type. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or IO[bytes] - :param request_options: Parameter group. Default value is None. - :type request_options: ~azure.search.documents.indexes.models.RequestOptions - :return: SynonymMap or the result of cls(response) - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SynonymMap] = kwargs.pop("cls", None) - - _x_ms_client_request_id = None - if request_options is not None: - _x_ms_client_request_id = request_options.x_ms_client_request_id - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _json = self._serialize.body(synonym_map, "SynonymMap") - - _request = build_create_request( - x_ms_client_request_id=_x_ms_client_request_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("SynonymMap", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed b/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/models/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py deleted file mode 100644 index 8d622df44258..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py +++ /dev/null @@ -1,847 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, List, Union, Optional, MutableMapping, cast - -from azure.core.rest import HttpRequest, HttpResponse -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace -from azure.core.paging import ItemPaged - -from .._api_versions import DEFAULT_VERSION -from ._generated import SearchServiceClient as _SearchServiceClient -from ._utils import ( - get_access_conditions, - normalize_endpoint, -) -from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy -from .._version import SDK_MONIKER -from .._search_client import SearchClient -from .models import ( - SearchIndex, - SynonymMap, - SearchAlias, - AnalyzeTextOptions, - AnalyzeResult, - IndexStatisticsSummary, - KnowledgeAgent, - KnowledgeSource, -) - - -class SearchIndexClient(HeadersMixin): # pylint:disable=too-many-public-methods - """A client to interact with Azure search service index. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) - self._credential = credential - self._audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=self._audience) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __enter__(self): - self._client.__enter__() - return self - - def __exit__(self, *args): - return self._client.__exit__(*args) - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - def get_search_client(self, index_name: str, **kwargs: Any) -> SearchClient: - """Return a client to perform operations on Search - - :param index_name: The name of the Search Index - :type index_name: str - :return: SearchClient object - :rtype: ~azure.search.documents.SearchClient - - """ - return SearchClient( - self._endpoint, - index_name, - self._credential, - audience=self._audience, - api_version=self._api_version, - **kwargs - ) - - @distributed_trace - def list_indexes(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> ItemPaged[SearchIndex]: - """List the indexes in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of indexes - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - indexes = self._client.indexes.list(cls=lambda objs: [SearchIndex._from_generated(x) for x in objs], **kwargs) - return cast(ItemPaged[SearchIndex], indexes) - - @distributed_trace - def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: - """List the index names in an Azure Search service. - - :return: List of index names - :rtype: ~azure.core.paging.ItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.indexes.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(ItemPaged[str], names) - - @distributed_trace - def get_index(self, name: str, **kwargs: Any) -> SearchIndex: - """Retrieve a named index in an Azure Search service - - :param name: The name of the index to retrieve. - :type name: str - :return: SearchIndex object - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud_operations.py - :start-after: [START get_index] - :end-before: [END get_index] - :language: python - :dedent: 4 - :caption: Get an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexes.get(name, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_index_statistics(self, index_name: str, **kwargs: Any) -> MutableMapping[str, Any]: - """Returns statistics for the given index, including a document count - and storage usage. - - :param index_name: The name of the index to retrieve. - :type index_name: str - :return: Statistics for the given index, including a document count and storage usage. - :rtype: Dict - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexes.get_statistics(index_name, **kwargs) - return result.as_dict() - - @distributed_trace - def delete_index( - self, - index: Union[str, SearchIndex], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. The model must be - provided instead of the name to use the access conditions. - - :param index: The index name or object to delete. - :type index: str or ~azure.search.documents.indexes.models.SearchIndex - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud_operations.py - :start-after: [START delete_index] - :end-before: [END delete_index] - :language: python - :dedent: 4 - :caption: Delete an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - try: - index_name = index.name # type: ignore - except AttributeError: - index_name = index - self._client.indexes.delete(index_name=index_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_index(self, index: SearchIndex, **kwargs: Any) -> SearchIndex: - """Creates a new search index. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :return: The index created - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud_operations.py - :start-after: [START create_index] - :end-before: [END create_index] - :language: python - :dedent: 4 - :caption: Creating a new index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_index = index._to_generated() # pylint:disable=protected-access - result = self._client.indexes.create(patched_index, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def create_or_update_index( - self, - index: SearchIndex, - allow_index_downtime: Optional[bool] = None, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. - :type allow_index_downtime: bool - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_crud_operations.py - :start-after: [START update_index] - :end-before: [END update_index] - :language: python - :dedent: 4 - :caption: Update an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - patched_index = index._to_generated() # pylint:disable=protected-access - result = self._client.indexes.create_or_update( - index_name=index.name, - index=patched_index, - allow_index_downtime=allow_index_downtime, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def analyze_text(self, index_name: str, analyze_request: AnalyzeTextOptions, **kwargs: Any) -> AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index for which to test an analyzer. - :type index_name: str - :param analyze_request: The text and analyzer or analysis components to test. - :type analyze_request: ~azure.search.documents.indexes.models.AnalyzeTextOptions - :return: AnalyzeResult - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_analyze_text.py - :start-after: [START simple_analyze_text] - :end-before: [END simple_analyze_text] - :language: python - :dedent: 4 - :caption: Analyze text - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexes.analyze( - index_name=index_name, - request=analyze_request._to_analyze_request(), # pylint:disable=protected-access - **kwargs - ) - return result - - @distributed_trace - def get_synonym_maps(self, *, select: Optional[List[str]] = None, **kwargs) -> List[SynonymMap]: - """List the Synonym Maps in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of synonym maps - :rtype: list[~azure.search.documents.indexes.models.SynonymMap] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_synonym_map_operations.py - :start-after: [START get_synonym_maps] - :end-before: [END get_synonym_maps] - :language: python - :dedent: 4 - :caption: List Synonym Maps - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SynonymMap, SynonymMap._from_generated(x)) for x in result.synonym_maps] - - @distributed_trace - def get_synonym_map_names(self, **kwargs: Any) -> List[str]: - """List the Synonym Map names in an Azure Search service. - - :return: List of synonym maps - :rtype: list[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - return [x.name for x in result.synonym_maps] - - @distributed_trace - def get_synonym_map(self, name: str, **kwargs: Any) -> SynonymMap: - """Retrieve a named Synonym Map in an Azure Search service - - :param name: The name of the Synonym Map to get - :type name: str - :return: The retrieved Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.ResourceNotFoundError: If the Synonym Map doesn't exist. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_synonym_map_operations.py - :start-after: [START get_synonym_map] - :end-before: [END get_synonym_map] - :language: python - :dedent: 4 - :caption: Get a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.synonym_maps.get(name, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def delete_synonym_map( - self, - synonym_map: Union[str, SynonymMap], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named Synonym Map in an Azure Search service. To use access conditions, - the SynonymMap model must be provided instead of the name. It is enough to provide - the name of the synonym map to delete unconditionally. - - :param synonym_map: The synonym map name or object to delete - :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_synonym_map_operations.py - :start-after: [START delete_synonym_map] - :end-before: [END delete_synonym_map] - :language: python - :dedent: 4 - :caption: Delete a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - try: - name = synonym_map.name # type: ignore - except AttributeError: - name = synonym_map - self._client.synonym_maps.delete(synonym_map_name=name, error_map=error_map, **kwargs) - - @distributed_trace - def create_synonym_map(self, synonym_map: SynonymMap, **kwargs: Any) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :return: The created Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_synonym_map_operations.py - :start-after: [START create_synonym_map] - :end-before: [END create_synonym_map] - :language: python - :dedent: 4 - :caption: Create a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = self._client.synonym_maps.create(patched_synonym_map, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def create_or_update_synonym_map( - self, - synonym_map: SynonymMap, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service, or update an - existing one. - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The created or updated Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = self._client.synonym_maps.create_or_update( - synonym_map_name=synonym_map.name, - synonym_map=patched_synonym_map, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_service_statistics(self, **kwargs: Any) -> MutableMapping[str, Any]: - """Get service level statistics for a search service. - - :return: Service statistics result. - :rtype: dict - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.get_service_statistics(**kwargs) - return result.as_dict() - - @distributed_trace - def list_index_stats_summary(self, **kwargs: Any) -> ItemPaged[IndexStatisticsSummary]: - """Get index level statistics for a search service. - - :return: Index statistics result. - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - result = self._client.get_index_stats_summary(**kwargs) - return cast(ItemPaged[IndexStatisticsSummary], result) - - @distributed_trace - def list_aliases(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> ItemPaged[SearchAlias]: - """List the aliases in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of Aliases - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - return cast(ItemPaged[SearchAlias], self._client.aliases.list(**kwargs)) - - @distributed_trace - def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: - """List the alias names in an Azure Search service. - - :return: List of alias names - :rtype: ~azure.core.paging.ItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.aliases.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(ItemPaged[str], names) - - @distributed_trace - def get_alias(self, name: str, **kwargs: Any) -> SearchAlias: - """ - - :param name: The name of the alias to retrieve. - :type name: str - :return: SearchAlias object - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.aliases.get(name, **kwargs) - return result - - @distributed_trace - def delete_alias( - self, - alias: Union[str, SearchAlias], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation - - :param alias: The alias name or object to delete. - :type alias: str or ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_alias_crud_operations.py - :start-after: [START delete_alias] - :end-before: [END delete_alias] - :language: python - :dedent: 4 - :caption: Deleting an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - try: - alias_name = alias.name # type: ignore - except AttributeError: - alias_name = alias - self._client.aliases.delete(alias_name=alias_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: - """Creates a new search alias. - - :param alias: The alias object. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :return: The alias created - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_alias_crud_operations.py - :start-after: [START create_alias] - :end-before: [END create_alias] - :language: python - :dedent: 4 - :caption: Creating a new alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.aliases.create(alias, **kwargs) - return result # pylint:disable=protected-access - - @distributed_trace - def create_or_update_alias( - self, alias: SearchAlias, *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any - ) -> SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias: The definition of the alias to create or update. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the alias has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the alias hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the alias already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_index_alias_crud_operations.py - :start-after: [START update_alias] - :end-before: [END update_alias] - :language: python - :dedent: 4 - :caption: Updating an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - result = self._client.aliases.create_or_update( - alias_name=alias.name, alias=alias, prefer="return=representation", error_map=error_map, **kwargs - ) - return result # pylint:disable=protected-access - - @distributed_trace - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> HttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access - - @distributed_trace - def delete_agent( - self, - agent: Union[str, KnowledgeAgent], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing agent. - - :param agent: The agent name or object to delete. - :type agent: str or ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(agent, match_condition) - kwargs.update(access_condition) - try: - agent_name = agent.name # type: ignore - except AttributeError: - agent_name = agent - self._client.knowledge_agents.delete(agent_name=agent_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_agent(self, agent: KnowledgeAgent, **kwargs: Any) -> KnowledgeAgent: - """Creates a new knowledge agent. - - :param agent: The agent object. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :return: The agent created - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_agents.create(agent, **kwargs) - return result - - @distributed_trace - def create_or_update_agent( - self, - agent: KnowledgeAgent, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeAgent: - """Creates a new knowledge agent or updates an agent if it already exists. - - :param agent: The agent object. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(agent, match_condition) - kwargs.update(access_condition) - result = self._client.knowledge_agents.create_or_update( - agent_name=agent.name, knowledge_agent=agent, prefer="return=representation", error_map=error_map, **kwargs - ) - return result - - @distributed_trace - def get_agent(self, name: str, **kwargs: Any) -> KnowledgeAgent: - """ - - :param name: The name of the agent to retrieve. - :type name: str - :return: KnowledgeAgent object - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_agents.get(name, **kwargs) - return result - - @distributed_trace - def list_agents(self, **kwargs: Any) -> ItemPaged[KnowledgeAgent]: - """List the agents in an Azure Search service. - - :return: List of Knowledge Agents - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(ItemPaged[KnowledgeAgent], self._client.knowledge_agents.list(**kwargs)) - - @distributed_trace - def delete_knowledge_source( - self, - knowledge_source: Union[str, KnowledgeSource], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param knowledge_source: The knowledge source name or object to delete. - :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - try: - source_name = knowledge_source.name # type: ignore - except AttributeError: - source_name = knowledge_source - self._client.knowledge_sources.delete(source_name=source_name, error_map=error_map, **kwargs) - - @distributed_trace - def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: Any) -> KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :return: The knowledge source created - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_sources.create(knowledge_source, **kwargs) - return result - - @distributed_trace - def create_or_update_knowledge_source( - self, - knowledge_source: KnowledgeSource, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeSource: - """Creates a new knowledge source or updates an existing one. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The knowledge source created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - result = self._client.knowledge_sources.create_or_update( - source_name=knowledge_source.name, - knowledge_source=knowledge_source, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return result - - @distributed_trace - def get_knowledge_source(self, name: str, **kwargs: Any) -> KnowledgeSource: - """ - - :param name: The name of the knowledge source to retrieve. - :type name: str - :return: KnowledgeSource object - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.knowledge_sources.get(name, **kwargs) - return result - - @distributed_trace - def list_knowledge_sources(self, **kwargs: Any) -> ItemPaged[KnowledgeSource]: - """List the knowledge sources in an Azure Search service. - - :return: List of Knowledge Sources - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(ItemPaged[KnowledgeSource], self._client.knowledge_sources.list(**kwargs)) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py deleted file mode 100644 index b41006ac5158..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_indexer_client.py +++ /dev/null @@ -1,741 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Optional, Sequence, Union, List, cast - -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.tracing.decorator import distributed_trace - -from ._generated import SearchServiceClient as _SearchServiceClient -from ._generated.models import ( - SkillNames, - SearchIndexerStatus, - DocumentKeysOrIds, - IndexerResyncOption, - IndexerResyncBody, -) -from ._utils import ( - get_access_conditions, - normalize_endpoint, -) -from .models import ( - SearchIndexer, - SearchIndexerSkillset, - EntityRecognitionSkillVersion, - SearchIndexerDataSourceConnection, - SentimentSkillVersion, -) -from .._api_versions import DEFAULT_VERSION -from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy -from .._version import SDK_MONIKER - - -class SearchIndexerClient(HeadersMixin): # pylint: disable=R0904 - """A client to interact with Azure search service Indexers. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - def __enter__(self) -> "SearchIndexerClient": - self._client.__enter__() - return self - - def __exit__(self, *args) -> None: - return self._client.__exit__(*args) - - def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return self._client.close() - - @distributed_trace - def create_indexer(self, indexer: SearchIndexer, **kwargs: Any) -> SearchIndexer: - """Creates a new SearchIndexer. - - :param indexer: The definition of the indexer to create. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START create_indexer] - :end-before: [END create_indexer] - :language: python - :dedent: 4 - :caption: Create a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = self._client.indexers.create(patched_indexer, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def create_or_update_indexer( - self, - indexer: SearchIndexer, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer: The definition of the indexer to create or update. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - name = indexer.name - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = self._client.indexers.create_or_update( - indexer_name=name, - indexer=patched_indexer, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_indexer(self, name: str, **kwargs: Any) -> SearchIndexer: - """Retrieves an indexer definition. - - :param name: The name of the indexer to retrieve. - :type name: str - :return: The SearchIndexer that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START get_indexer] - :end-before: [END get_indexer] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexers.get(name, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace - def get_indexers(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> Sequence[SearchIndexer]: - """Lists all indexers available for a search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of all the SearchIndexers. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START list_indexer] - :end-before: [END list_indexer] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SearchIndexer, SearchIndexer._from_generated(index)) for index in result.indexers] - - @distributed_trace - def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: - """Lists all indexer names available for a search service. - - :return: List of all the SearchIndexers. - :rtype: list[str] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START list_indexer] - :end-before: [END list_indexer] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - return [x.name for x in result.indexers] - - @distributed_trace - def delete_indexer( - self, - indexer: Union[str, SearchIndexer], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an indexer. To use access conditions, the SearchIndexer model - must be provided instead of the name. It is enough to provide - the name of the indexer to delete unconditionally. - - :param indexer: The indexer to delete. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START delete_indexer] - :end-before: [END delete_indexer] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - self._client.indexers.delete(name, error_map=error_map, **kwargs) - - @distributed_trace - def run_indexer(self, name: str, **kwargs: Any) -> None: - """Run an indexer. - - :param name: The name of the indexer to run. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START run_indexer] - :end-before: [END run_indexer] - :language: python - :dedent: 4 - :caption: Run a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - self._client.indexers.run(name, **kwargs) - - @distributed_trace - def reset_indexer(self, name: str, **kwargs: Any) -> None: - """Resets the change tracking state associated with an indexer. - - :param name: The name of the indexer to reset. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START reset_indexer] - :end-before: [END reset_indexer] - :language: python - :dedent: 4 - :caption: Reset a SearchIndexer's change tracking state - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - self._client.indexers.reset(name, **kwargs) - - @distributed_trace - def reset_documents( - self, - indexer: Union[str, SearchIndexer], - keys_or_ids: DocumentKeysOrIds, - *, - overwrite: bool = False, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - :param indexer: The indexer to reset documents for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param keys_or_ids: - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :return: None, or the result of cls(response) - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. The default is false. - :paramtype overwrite: bool - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["keys_or_ids"] = keys_or_ids - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - return self._client.indexers.reset_docs(name, overwrite=overwrite, **kwargs) - - @distributed_trace - def resync( - self, - indexer: Union[str, SearchIndexer], - indexer_resync_options: List[Union[str, IndexerResyncOption]], - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - :param indexer: The indexer to resync for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param indexer_resync_options: Required. - :type indexer_resync_options: list[str or - ~azure.search.documents.indexes.models.IndexerResyncOption] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - - # Create IndexerResyncBody from the list of options - resync_body = IndexerResyncBody(options=indexer_resync_options) - self._client.indexers.resync(name, resync_body, **kwargs) - - @distributed_trace - def get_indexer_status(self, name: str, **kwargs: Any) -> SearchIndexerStatus: - """Get the status of the indexer. - - :param name: The name of the indexer to fetch the status. - :type name: str - - :return: SearchIndexerStatus - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START get_indexer_status] - :end-before: [END get_indexer_status] - :language: python - :dedent: 4 - :caption: Get a SearchIndexer's status - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return self._client.indexers.get_status(name, **kwargs) - - @distributed_trace - def create_data_source_connection( - self, data_source_connection: SearchIndexerDataSourceConnection, **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection. - - :param data_source_connection: The definition of the data source connection to create. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_data_source_operations.py - :start-after: [START create_data_source_connection] - :end-before: [END create_data_source_connection] - :language: python - :dedent: 4 - :caption: Create a Data Source - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - packed_data_source = data_source_connection._to_generated() - result = self._client.data_sources.create(packed_data_source, **kwargs) - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace - def create_or_update_data_source_connection( - self, - data_source_connection: SearchIndexerDataSourceConnection, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_connection: The definition of the data source connection to create or update. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - """ - - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(data_source_connection, match_condition) - kwargs.update(access_condition) - name = data_source_connection.name - packed_data_source = data_source_connection._to_generated() # pylint:disable=protected-access - result = self._client.data_sources.create_or_update( - data_source_name=name, - data_source=packed_data_source, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - **kwargs - ) - # pylint:disable=protected-access - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace - def get_data_source_connection(self, name: str, **kwargs: Any) -> SearchIndexerDataSourceConnection: - """Retrieves a data source connection definition. - - :param name: The name of the data source connection to retrieve. - :type name: str - :return: The SearchIndexerDataSourceConnection that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_data_source_operations.py - :start-after: [START get_data_source_connection] - :end-before: [END get_data_source_connection] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.data_sources.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace - def get_data_source_connections( - self, *, select: Optional[List[str]] = None, **kwargs: Any - ) -> Sequence[SearchIndexerDataSourceConnection]: - """Lists all data source connections available for a search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of all the data source connections. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_data_source_operations.py - :start-after: [START list_data_source_connection] - :end-before: [END list_data_source_connection] - :language: python - :dedent: 4 - :caption: List all the SearchIndexerDataSourceConnections - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - # pylint:disable=protected-access - return [ - cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(x)) - for x in result.data_sources - ] - - @distributed_trace - def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: - """Lists all data source connection names available for a search service. - - :return: List of all the data source connection names. - :rtype: list[str] - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - return [x.name for x in result.data_sources] - - @distributed_trace - def delete_data_source_connection( - self, - data_source_connection: Union[str, SearchIndexerDataSourceConnection], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a data source connection. To use access conditions, the SearchIndexerDataSourceConnection - model must be provided instead of the name. It is enough to provide the name of the data source connection - to delete unconditionally - - :param data_source_connection: The data source connection to delete. - :type data_source_connection: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_data_source_operations.py - :start-after: [START delete_data_source_connection] - :end-before: [END delete_data_source_connection] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(data_source_connection, match_condition) - kwargs.update(access_condition) - try: - name = data_source_connection.name # type: ignore - except AttributeError: - name = data_source_connection - self._client.data_sources.delete(data_source_name=name, error_map=error_map, **kwargs) - - @distributed_trace - def get_skillsets(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[SearchIndexerSkillset]: - # pylint:disable=protected-access - """List the SearchIndexerSkillsets in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of SearchIndexerSkillsets - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [ - cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(skillset)) - for skillset in result.skillsets - ] - - @distributed_trace - def get_skillset_names(self, **kwargs: Any) -> List[str]: - """List the SearchIndexerSkillset names in an Azure Search service. - - :return: List of SearchIndexerSkillset names - :rtype: list[str] - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [x.name for x in result.skillsets] - - @distributed_trace - def get_skillset(self, name: str, **kwargs: Any) -> SearchIndexerSkillset: - """Retrieve a named SearchIndexerSkillset in an Azure Search service - - :param name: The name of the SearchIndexerSkillset to get - :type name: str - :return: The retrieved SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.ResourceNotFoundError: If the skillset cannot be found. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self._client.skillsets.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace - def delete_skillset( - self, - skillset: Union[str, SearchIndexerSkillset], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named SearchIndexerSkillset in an Azure Search service. To use access conditions, - the SearchIndexerSkillset model must be provided instead of the name. It is enough to provide - the name of the skillset to delete unconditionally - - :param skillset: The SearchIndexerSkillset to delete - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - self._client.skillsets.delete(name, error_map=error_map, **kwargs) - - @distributed_trace - def create_skillset(self, skillset: SearchIndexerSkillset, **kwargs: Any) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service - - :param skillset: The SearchIndexerSkillset object to create - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :return: The created SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - _validate_skillset(skillset) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - - result = self._client.skillsets.create(skillset_gen, **kwargs) # type: ignore - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace - def create_or_update_skillset( - self, - skillset: SearchIndexerSkillset, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service, or update an - existing one. - - :param skillset: The SearchIndexerSkillset object to create or update - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created or updated SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - _validate_skillset(skillset) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - - result = self._client.skillsets.create_or_update( - skillset_name=skillset.name, - skillset=skillset_gen, # type: ignore - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace - def reset_skills(self, skillset: Union[str, SearchIndexerSkillset], skill_names: List[str], **kwargs: Any) -> None: - """Reset an existing skillset in a search service. - - :param skillset: The SearchIndexerSkillset to reset - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param skill_names: the names of skills to be reset. - :type skill_names: List[str] - :return: None, or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - names = SkillNames(skill_names=skill_names) - return self._client.skillsets.reset_skills(skillset_name=name, skill_names=names, **kwargs) - - -def _validate_skillset(skillset: SearchIndexerSkillset): - """Validates any multi-version skills in the skillset to verify that unsupported - parameters are not supplied by the user. - - :param skillset: The skillset to validate - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - """ - skills = getattr(skillset, "skills", None) - if not skills: - return - - error_strings = [] - for skill in skills: - try: - skill_version = skill.get("skill_version") - except AttributeError: - skill_version = getattr(skill, "skill_version", None) - if not skill_version: - continue - if skill_version == SentimentSkillVersion.V3: - unsupported = [] - elif skill_version == EntityRecognitionSkillVersion.V3: - unsupported = ["include_typeless_entities"] - - errors = [] - for item in unsupported: - try: - if skill.get(item, None): - errors.append(item) - except AttributeError: - if skill.__dict__.get(item, None): - errors.append(item) - if errors: - error_strings.append( - "Unsupported parameters for skill version {}: {}".format(skill_version, ", ".join(errors)) - ) - if error_strings: - raise ValueError("\n".join(error_strings)) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py deleted file mode 100644 index bfe9a82a8357..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils.py +++ /dev/null @@ -1,80 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -from typing import Optional, Any, Tuple, Dict -from azure.core import MatchConditions -from azure.core.exceptions import ( - ClientAuthenticationError, - ResourceExistsError, - ResourceNotFoundError, - ResourceModifiedError, - ResourceNotModifiedError, -) - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: MatchConditions) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: str, match_condition: MatchConditions) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None - - -def get_access_conditions( - model: Any, match_condition: MatchConditions = MatchConditions.Unconditionally -) -> Tuple[Dict[int, Any], Dict[str, Optional[str]]]: - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError} - - if isinstance(model, str): - if match_condition is not MatchConditions.Unconditionally: - raise ValueError("A model must be passed to use access conditions") - return error_map, {} - - try: - if_match = prep_if_match(model.e_tag, match_condition) - if_none_match = prep_if_none_match(model.e_tag, match_condition) - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - if match_condition == MatchConditions.IfModified: - error_map[304] = ResourceNotModifiedError - error_map[412] = ResourceNotModifiedError - if match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - if match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError - return error_map, {"if_match": if_match, "if_none_match": if_none_match} - except AttributeError as ex: - raise ValueError("Unable to get e_tag from the model") from ex - - -def normalize_endpoint(endpoint): - try: - if not endpoint.lower().startswith("http"): - endpoint = "https://" + endpoint - elif not endpoint.lower().startswith("https"): - raise ValueError("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.") - return endpoint - except AttributeError as ex: - raise ValueError("Endpoint must be a string.") from ex diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/__init__.py similarity index 52% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/__init__.py index f986b371549e..8026245c2abc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/__init__.py @@ -1,4 +1,6 @@ # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/model_base.py @@ -0,0 +1,1237 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + return getattr(self._type, "args", [None])[0] + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + item = obj.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + return _deserialize(self._type, _serialize(item, self._format), rf=self) + + def __set__(self, obj: Model, value) -> None: + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/serialization.py similarity index 99% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/serialization.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/serialization.py index 003e1c89fb35..45a3e44e45cb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_utils/serialization.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/serialization.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -785,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py index be7617562446..a5266d617dfe 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py @@ -1,33 +1,29 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._search_index_client import SearchIndexClient -from ._search_indexer_client import SearchIndexerClient +from typing import TYPE_CHECKING -__all__ = ( +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import SearchIndexClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ "SearchIndexClient", - "SearchIndexerClient", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py similarity index 62% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py index d0f1b99796c9..52a887802d62 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_search_service_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py @@ -1,67 +1,74 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import SearchServiceClientConfiguration +from ..._utils.serialization import Deserializer, Serializer +from ._configuration import SearchIndexClientConfiguration from .operations import ( + AgentsOperations, AliasesOperations, DataSourcesOperations, IndexersOperations, IndexesOperations, - KnowledgeAgentsOperations, - KnowledgeSourcesOperations, SkillsetsOperations, + SourcesOperations, SynonymMapsOperations, - _SearchServiceClientOperationsMixin, + _SearchIndexClientOperationsMixin, ) +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class SearchServiceClient(_SearchServiceClientOperationsMixin): # pylint: disable=too-many-instance-attributes - """Client that can be used to manage and query indexes and documents, as well as manage other - resources, on a search service. - :ivar knowledge_agents: KnowledgeAgentsOperations operations - :vartype knowledge_agents: - azure.search.documents.indexes.aio.operations.KnowledgeAgentsOperations - :ivar knowledge_sources: KnowledgeSourcesOperations operations - :vartype knowledge_sources: - azure.search.documents.indexes.aio.operations.KnowledgeSourcesOperations +class SearchIndexClient(_SearchIndexClientOperationsMixin): # pylint: disable=too-many-instance-attributes + """SearchIndexClient. + :ivar data_sources: DataSourcesOperations operations - :vartype data_sources: azure.search.documents.indexes.aio.operations.DataSourcesOperations + :vartype data_sources: azure.search.documents.aio.operations.DataSourcesOperations :ivar indexers: IndexersOperations operations - :vartype indexers: azure.search.documents.indexes.aio.operations.IndexersOperations + :vartype indexers: azure.search.documents.aio.operations.IndexersOperations :ivar skillsets: SkillsetsOperations operations - :vartype skillsets: azure.search.documents.indexes.aio.operations.SkillsetsOperations + :vartype skillsets: azure.search.documents.aio.operations.SkillsetsOperations :ivar synonym_maps: SynonymMapsOperations operations - :vartype synonym_maps: azure.search.documents.indexes.aio.operations.SynonymMapsOperations + :vartype synonym_maps: azure.search.documents.aio.operations.SynonymMapsOperations :ivar indexes: IndexesOperations operations - :vartype indexes: azure.search.documents.indexes.aio.operations.IndexesOperations + :vartype indexes: azure.search.documents.aio.operations.IndexesOperations :ivar aliases: AliasesOperations operations - :vartype aliases: azure.search.documents.indexes.aio.operations.AliasesOperations - :param endpoint: The endpoint URL of the search service. Required. + :vartype aliases: azure.search.documents.aio.operations.AliasesOperations + :ivar agents: AgentsOperations operations + :vartype agents: azure.search.documents.aio.operations.AgentsOperations + :ivar sources: SourcesOperations operations + :vartype sources: azure.search.documents.aio.operations.SourcesOperations + :param endpoint: Service host. Required. :type endpoint: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: _endpoint = "{endpoint}" - self._config = SearchServiceClientConfiguration(endpoint=endpoint, **kwargs) + self._config = SearchIndexClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -82,24 +89,19 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.knowledge_agents = KnowledgeAgentsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.knowledge_sources = KnowledgeSourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) self.data_sources = DataSourcesOperations(self._client, self._config, self._serialize, self._deserialize) self.indexers = IndexersOperations(self._client, self._config, self._serialize, self._deserialize) self.skillsets = SkillsetsOperations(self._client, self._config, self._serialize, self._deserialize) self.synonym_maps = SynonymMapsOperations(self._client, self._config, self._serialize, self._deserialize) self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) self.aliases = AliasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.agents = AgentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.sources = SourcesOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -107,7 +109,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py new file mode 100644 index 000000000000..a511669d940d --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py @@ -0,0 +1,74 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from ..._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py deleted file mode 100644 index db82fab940b0..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_index_client.py +++ /dev/null @@ -1,841 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, Any, List, Optional, MutableMapping, cast - -from azure.core.rest import HttpRequest, AsyncHttpResponse -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.async_paging import AsyncItemPaged -from .._generated.aio import SearchServiceClient as _SearchServiceClient -from ...aio._search_client_async import SearchClient -from .._utils import ( - get_access_conditions, - normalize_endpoint, -) -from ..._api_versions import DEFAULT_VERSION -from ..._headers_mixin import HeadersMixin -from ..._utils import get_authentication_policy -from ..._version import SDK_MONIKER -from ..models import ( - SearchIndex, - SynonymMap, - SearchAlias, - AnalyzeResult, - AnalyzeTextOptions, - IndexStatisticsSummary, - KnowledgeAgent, - KnowledgeSource, -) - - -class SearchIndexClient(HeadersMixin): # pylint:disable=too-many-public-methods - """A client to interact with Azure search service Indexes. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) - self._credential = credential - self._audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=self._audience, is_async=True) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - async def __aenter__(self) -> "SearchIndexClient": - await self._client.__aenter__() # pylint:disable=no-member - return self - - async def __aexit__(self, *args: Any) -> None: - return await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - def get_search_client(self, index_name: str, **kwargs: Any) -> SearchClient: - """Return a client to perform operations on Search. - - :param index_name: The name of the Search Index - :type index_name: str - :return: SearchClient - :rtype: ~azure.search.documents.aio.SearchClient - """ - return SearchClient( - self._endpoint, - index_name, - self._credential, - audience=self._audience, - api_version=self._api_version, - **kwargs - ) - - @distributed_trace - def list_indexes(self, *, select: Optional[List[str]] = None, **kwargs) -> AsyncItemPaged[SearchIndex]: - """List the indexes in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of indexes - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - indexes = self._client.indexes.list(cls=lambda objs: [SearchIndex._from_generated(x) for x in objs], **kwargs) - return cast(AsyncItemPaged[SearchIndex], indexes) - - @distributed_trace - def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: - """List the index names in an Azure Search service. - - :return: List of index names - :rtype: ~azure.core.async_paging.AsyncItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.indexes.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(AsyncItemPaged[str], names) - - @distributed_trace_async - async def get_index(self, name: str, **kwargs: Any) -> SearchIndex: - """Retrieve a named index in an Azure Search service - - :param name: The name of the index to retrieve. - :type name: str - :return: SearchIndex object - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_operations_async.py - :start-after: [START get_index_async] - :end-before: [END get_index_async] - :language: python - :dedent: 4 - :caption: Get an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexes.get(name, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_index_statistics(self, index_name: str, **kwargs: Any) -> MutableMapping[str, Any]: - """Returns statistics for the given index, including a document count - and storage usage. - - :param index_name: The name of the index to retrieve. - :type index_name: str - :return: Statistics for the given index, including a document count and storage usage. - :rtype: Dict - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexes.get_statistics(index_name, **kwargs) - return result.as_dict() - - @distributed_trace_async - async def delete_index( - self, - index: Union[str, SearchIndex], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. The model must be - provided instead of the name to use the access conditions - - :param index: The index name or object to delete. - :type index: str or ~azure.search.documents.indexes.models.SearchIndex - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_operations_async.py - :start-after: [START delete_index_async] - :end-before: [END delete_index_async] - :language: python - :dedent: 4 - :caption: Delete an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - try: - index_name = index.name # type: ignore - except AttributeError: - index_name = index - await self._client.indexes.delete(index_name=index_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_index(self, index: SearchIndex, **kwargs: Any) -> SearchIndex: - """Creates a new search index. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :return: The index created - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_operations_async.py - :start-after: [START create_index_async] - :end-before: [END create_index_async] - :language: python - :dedent: 4 - :caption: Creating a new index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_index = index._to_generated() # pylint:disable=protected-access - result = await self._client.indexes.create(patched_index, **kwargs) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_index( - self, - index: SearchIndex, - allow_index_downtime: Optional[bool] = None, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index: The index object. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. - :type allow_index_downtime: bool - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index has not been modified. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index is not found. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_crud_operations_async.py - :start-after: [START update_index_async] - :end-before: [END update_index_async] - :language: python - :dedent: 4 - :caption: Update an index. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(index, match_condition) - kwargs.update(access_condition) - patched_index = index._to_generated() # pylint:disable=protected-access - result = await self._client.indexes.create_or_update( - index_name=index.name, - index=patched_index, - allow_index_downtime=allow_index_downtime, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def analyze_text(self, index_name: str, analyze_request: AnalyzeTextOptions, **kwargs: Any) -> AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index for which to test an analyzer. - :type index_name: str - :param analyze_request: The text and analyzer or analysis components to test. - :type analyze_request: ~azure.search.documents.indexes.models.AnalyzeTextOptions - :return: AnalyzeResult - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_analyze_text_async.py - :start-after: [START simple_analyze_text_async] - :end-before: [END simple_analyze_text_async] - :language: python - :dedent: 4 - :caption: Analyze text - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexes.analyze( - index_name=index_name, - request=analyze_request._to_analyze_request(), # pylint:disable=protected-access - **kwargs - ) - return result - - @distributed_trace_async - async def get_synonym_maps(self, *, select: Optional[List[str]] = None, **kwargs) -> List[SynonymMap]: - """List the Synonym Maps in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: List[str] - :return: List of synonym maps - :rtype: List[~azure.search.documents.indexes.models.SynonymMap] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_synonym_map_operations_async.py - :start-after: [START get_synonym_maps_async] - :end-before: [END get_synonym_maps_async] - :language: python - :dedent: 4 - :caption: List Synonym Maps - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SynonymMap, SynonymMap._from_generated(x)) for x in result.synonym_maps] - - @distributed_trace_async - async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: - """List the Synonym Map names in an Azure Search service. - - :return: List of synonym map names - :rtype: List[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.synonym_maps.list(**kwargs) - assert result.synonym_maps is not None # Hint for mypy - return [x.name for x in result.synonym_maps] - - @distributed_trace_async - async def get_synonym_map(self, name: str, **kwargs: Any) -> SynonymMap: - """Retrieve a named Synonym Map in an Azure Search service - - :param name: The name of the Synonym Map to get - :type name: str - :return: The retrieved Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.ResourceNotFoundError: If the Synonym Map doesn't exist. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_synonym_map_operations_async.py - :start-after: [START get_synonym_map_async] - :end-before: [END get_synonym_map_async] - :language: python - :dedent: 4 - :caption: Get a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.synonym_maps.get(name, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def delete_synonym_map( - self, - synonym_map: Union[str, SynonymMap], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named Synonym Map in an Azure Search service. To use access conditions, - the SynonymMap model must be provided instead of the name. It is enough to provide - the name of the synonym map to delete unconditionally. - - :param synonym_map: The synonym map name or object to delete - :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_synonym_map_operations_async.py - :start-after: [START delete_synonym_map_async] - :end-before: [END delete_synonym_map_async] - :language: python - :dedent: 4 - :caption: Delete a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - try: - name = synonym_map.name # type: ignore - except AttributeError: - name = synonym_map - await self._client.synonym_maps.delete(synonym_map_name=name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_synonym_map(self, synonym_map: SynonymMap, **kwargs: Any) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :return: The created Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_synonym_map_operations_async.py - :start-after: [START create_synonym_map_async] - :end-before: [END create_synonym_map_async] - :language: python - :dedent: 4 - :caption: Create a Synonym Map - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = await self._client.synonym_maps.create(patched_synonym_map, **kwargs) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_synonym_map( - self, - synonym_map: SynonymMap, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> SynonymMap: - """Create a new Synonym Map in an Azure Search service, or update an - existing one. - - :param synonym_map: The Synonym Map object - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The created or updated Synonym Map - :rtype: ~azure.search.documents.indexes.models.SynonymMap - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(synonym_map, match_condition) - kwargs.update(access_condition) - patched_synonym_map = synonym_map._to_generated() # pylint:disable=protected-access - result = await self._client.synonym_maps.create_or_update( - synonym_map_name=synonym_map.name, - synonym_map=patched_synonym_map, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_service_statistics(self, **kwargs) -> MutableMapping[str, Any]: - """Get service level statistics for a search service. - - :return: Service statistics result - :rtype: dict - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.get_service_statistics(**kwargs) - return result.as_dict() - - @distributed_trace - def list_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged[IndexStatisticsSummary]: - """Get index level statistics for a search service. - - :return: Index statistics result. - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - result = self._client.get_index_stats_summary(**kwargs) - return cast(AsyncItemPaged[IndexStatisticsSummary], result) - - @distributed_trace - def list_aliases(self, *, select: Optional[List[str]] = None, **kwargs) -> AsyncItemPaged[SearchAlias]: - """List the aliases in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of Aliases - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - # pylint:disable=protected-access - return cast(AsyncItemPaged[SearchAlias], self._client.aliases.list(**kwargs)) - - @distributed_trace - def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: - """List the alias names in an Azure Search service. - - :return: List of alias names - :rtype: ~azure.core.async_paging.AsyncItemPaged[str] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - - names = self._client.aliases.list(cls=lambda objs: [x.name for x in objs], **kwargs) - return cast(AsyncItemPaged[str], names) - - @distributed_trace_async - async def get_alias(self, name: str, **kwargs) -> SearchAlias: - """Retrieve a named alias in an Azure Search service - - :param name: The name of the alias to retrieve. - :type name: str - :return: SearchAlias object - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.aliases.get(name, **kwargs) - return result - - @distributed_trace_async - async def delete_alias( - self, - alias: Union[str, SearchAlias], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. - This operation is permanent, with no recovery option. The mapped index is untouched by this operation - - :param alias: The alias name or object to delete. - :type alias: str or ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_alias_crud_operations_async.py - :start-after: [START delete_alias_async] - :end-before: [END delete_alias_async] - :language: python - :dedent: 4 - :caption: Delete an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - try: - alias_name = alias.name # type: ignore - except AttributeError: - alias_name = alias - await self._client.aliases.delete(alias_name=alias_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: - """Creates a new search alias. - - :param alias: The alias object. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :return: The alias created - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_alias_crud_operations_async.py - :start-after: [START create_alias_async] - :end-before: [END create_alias_async] - :language: python - :dedent: 4 - :caption: Create an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.aliases.create(alias, **kwargs) - return result # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_alias( - self, alias: SearchAlias, *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any - ) -> SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias: The definition of the alias to create or update. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the alias has been modified. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the alias has not been modified. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the alias is not found. - :raises ~azure.core.exceptions.ResourceExistsError: If the alias already exists. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_index_alias_crud_operations_async.py - :start-after: [START update_alias_async] - :end-before: [END update_alias_async] - :language: python - :dedent: 4 - :caption: Update an alias. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(alias, match_condition) - kwargs.update(access_condition) - result = await self._client.aliases.create_or_update( - alias_name=alias.name, alias=alias, prefer="return=representation", error_map=error_map, **kwargs - ) - return result # pylint:disable=protected-access - - @distributed_trace_async - async def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> AsyncHttpResponse: - """Runs a network request using the client's existing pipeline. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - request.headers = self._merge_client_headers(request.headers) - return await self._client._send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access - - @distributed_trace_async - async def delete_agent( - self, - agent: Union[str, KnowledgeAgent], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing agent. - - :param agent: The agent name or object to delete. - :type agent: str or ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(agent, match_condition) - kwargs.update(access_condition) - try: - agent_name = agent.name # type: ignore - except AttributeError: - agent_name = agent - await self._client.knowledge_agents.delete(agent_name=agent_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_agent(self, agent: KnowledgeAgent, **kwargs: Any) -> KnowledgeAgent: - """Creates a new knowledge agent. - - :param agent: The agent object. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :return: The agent created - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_agents.create(agent, **kwargs) - return result - - @distributed_trace_async - async def create_or_update_agent( - self, - agent: KnowledgeAgent, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeAgent: - """Creates a new knowledge agent or updates an agent if it already exists. - - :param agent: The agent object. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The index created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(agent, match_condition) - kwargs.update(access_condition) - result = await self._client.knowledge_agents.create_or_update( - agent_name=agent.name, knowledge_agent=agent, prefer="return=representation", error_map=error_map, **kwargs - ) - return result - - @distributed_trace_async - async def get_agent(self, name: str, **kwargs: Any) -> KnowledgeAgent: - """ - - :param name: The name of the agent to retrieve. - :type name: str - :return: KnowledgeAgent object - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_agents.get(name, **kwargs) - return result - - @distributed_trace - def list_agents(self, **kwargs) -> AsyncItemPaged[KnowledgeAgent]: - """List the agents in an Azure Search service. - - :return: List of Knowledge Agents - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(AsyncItemPaged[KnowledgeAgent], self._client.knowledge_agents.list(**kwargs)) - - @distributed_trace_async - async def delete_knowledge_source( - self, - knowledge_source: Union[str, KnowledgeSource], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an existing knowledge source. - - :param knowledge_source: The knowledge source name or object to delete. - :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - try: - source_name = knowledge_source.name # type: ignore - except AttributeError: - source_name = knowledge_source - await self._client.knowledge_sources.delete(source_name=source_name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: Any) -> KnowledgeSource: - """Creates a new knowledge source. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :return: The knowledge source created - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_sources.create(knowledge_source, **kwargs) - return result - - @distributed_trace_async - async def create_or_update_knowledge_source( - self, - knowledge_source: KnowledgeSource, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> KnowledgeSource: - """Creates a new knowledge source or updates an existing one. - - :param knowledge_source: The knowledge source object. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The knowledge source created or updated - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceModifiedError: If the index has been modified in the server. - :raises ~azure.core.exceptions.ResourceNotModifiedError: If the index hasn't been modified in the server. - :raises ~azure.core.exceptions.ResourceNotFoundError: If the index doesn't exist. - :raises ~azure.core.exceptions.ResourceExistsError: If the index already exists. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(knowledge_source, match_condition) - kwargs.update(access_condition) - result = await self._client.knowledge_sources.create_or_update( - source_name=knowledge_source.name, - knowledge_source=knowledge_source, - prefer="return=representation", - error_map=error_map, - **kwargs - ) - return result - - @distributed_trace_async - async def get_knowledge_source(self, name: str, **kwargs: Any) -> KnowledgeSource: - """ - - :param name: The name of the knowledge source to retrieve. - :type name: str - :return: KnowledgeSource object - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.knowledge_sources.get(name, **kwargs) - return result - - @distributed_trace - def list_knowledge_sources(self, **kwargs: Any) -> AsyncItemPaged[KnowledgeSource]: - """List the knowledge sources in an Azure Search service. - - :return: List of Knowledge Sources - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] - :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - return cast(AsyncItemPaged[KnowledgeSource], self._client.knowledge_sources.list(**kwargs)) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py deleted file mode 100644 index 97d0505db5af..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_search_indexer_client.py +++ /dev/null @@ -1,691 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Union, Any, Optional, Sequence, List, cast - -from azure.core import MatchConditions -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.tracing.decorator_async import distributed_trace_async - -from .._generated.aio import SearchServiceClient as _SearchServiceClient -from .._generated.models import ( - SkillNames, - SearchIndexerStatus, - DocumentKeysOrIds, - IndexerResyncOption, - IndexerResyncBody, -) -from ..models import SearchIndexer, SearchIndexerSkillset, SearchIndexerDataSourceConnection -from .._utils import ( - get_access_conditions, - normalize_endpoint, -) -from ..._api_versions import DEFAULT_VERSION -from ..._headers_mixin import HeadersMixin -from ..._utils import get_authentication_policy -from ..._version import SDK_MONIKER - - -class SearchIndexerClient(HeadersMixin): # pylint: disable=R0904 - """A client to interact with Azure search service Indexers. - - :param endpoint: The URL endpoint of an Azure search service - :type endpoint: str - :param credential: A credential to authorize search client requests - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Search API version to use for requests. - :keyword str audience: sets the Audience to use for authentication with Microsoft Entra ID. The - audience is not considered when using a shared key. If audience is not provided, the public cloud audience - will be assumed. - """ - - _ODATA_ACCEPT: str = "application/json;odata.metadata=minimal" - _client: _SearchServiceClient - - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs) -> None: - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._endpoint = normalize_endpoint(endpoint) # type: str - self._credential = credential - audience = kwargs.pop("audience", None) - if isinstance(credential, AzureKeyCredential): - self._aad = False - self._client = _SearchServiceClient( - endpoint=endpoint, sdk_moniker=SDK_MONIKER, api_version=self._api_version, **kwargs - ) - else: - self._aad = True - authentication_policy = get_authentication_policy(credential, audience=audience, is_async=True) - self._client = _SearchServiceClient( - endpoint=endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - api_version=self._api_version, - **kwargs - ) - - async def __aenter__(self) -> "SearchIndexerClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *args) -> None: - return await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close the session. - - :return: None - :rtype: None - """ - return await self._client.close() - - @distributed_trace_async - async def create_indexer(self, indexer: SearchIndexer, **kwargs: Any) -> SearchIndexer: - """Creates a new SearchIndexer. - - :param indexer: The definition of the indexer to create. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START create_indexer_async] - :end-before: [END create_indexer_async] - :language: python - :dedent: 4 - :caption: Create a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = await self._client.indexers.create(patched_indexer, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def create_or_update_indexer( - self, - indexer: SearchIndexer, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexer: - """Creates a new indexer or updates a indexer if it already exists. - - :param indexer: The definition of the indexer to create or update. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - name = indexer.name - patched_indexer = indexer._to_generated() # pylint:disable=protected-access - result = await self._client.indexers.create_or_update( - indexer_name=name, - indexer=patched_indexer, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_indexer(self, name: str, **kwargs: Any) -> SearchIndexer: - """Retrieves a indexer definition. - - :param name: The name of the indexer to retrieve. - :type name: str - :return: The SearchIndexer that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START get_indexer_async] - :end-before: [END get_indexer_async] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexers.get(name, **kwargs) - return cast(SearchIndexer, SearchIndexer._from_generated(result)) # pylint:disable=protected-access - - @distributed_trace_async - async def get_indexers(self, *, select: Optional[List[str]] = None, **kwargs) -> Sequence[SearchIndexer]: - """Lists all indexers available for a search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of all the SearchIndexers. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START list_indexer_async] - :end-before: [END list_indexer_async] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - # pylint:disable=protected-access - return [cast(SearchIndexer, SearchIndexer._from_generated(index)) for index in result.indexers] - - @distributed_trace_async - async def get_indexer_names(self, **kwargs) -> Sequence[str]: - """Lists all indexer names available for a search service. - - :return: List of all the SearchIndexer names. - :rtype: list[str] - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.indexers.list(**kwargs) - assert result.indexers is not None # Hint for mypy - return [x.name for x in result.indexers] - - @distributed_trace_async - async def delete_indexer( - self, - indexer: Union[str, SearchIndexer], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes an indexer. To use access conditions, the SearchIndexer model - must be provided instead of the name. It is enough to provide - the name of the indexer to delete unconditionally. - - :param indexer: The name or the indexer object to delete. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START delete_indexer_async] - :end-before: [END delete_indexer_async] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(indexer, match_condition) - kwargs.update(access_condition) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - await self._client.indexers.delete(name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def run_indexer(self, name: str, **kwargs: Any) -> None: - """Run an indexer. - - :param name: The name of the indexer to run. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START run_indexer_async] - :end-before: [END run_indexer_async] - :language: python - :dedent: 4 - :caption: Run a SearchIndexer - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - await self._client.indexers.run(name, **kwargs) - - @distributed_trace_async - async def reset_indexer(self, name: str, **kwargs: Any) -> None: - """Resets the change tracking state associated with an indexer. - - :param name: The name of the indexer to reset. - :type name: str - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START reset_indexer_async] - :end-before: [END reset_indexer_async] - :language: python - :dedent: 4 - :caption: Reset a SearchIndexer's change tracking state - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - await self._client.indexers.reset(name, **kwargs) - - @distributed_trace_async - async def reset_documents( - self, - indexer: Union[str, SearchIndexer], - keys_or_ids: DocumentKeysOrIds, - *, - overwrite: bool = False, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - :param indexer: The indexer to reset documents for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param keys_or_ids: - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :return: None, or the result of cls(response) - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. The default is false. - :paramtype overwrite: bool - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - kwargs["keys_or_ids"] = keys_or_ids - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - await self._client.indexers.reset_docs(name, overwrite=overwrite, **kwargs) - return - - @distributed_trace_async - async def resync( - self, - indexer: Union[str, SearchIndexer], - indexer_resync_options: List[Union[str, IndexerResyncOption]], - **kwargs: Any - ) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer. - - :param indexer: The indexer to resync for. - :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer - :param indexer_resync_options: Required. - :type indexer_resync_options: list[str or - ~azure.search.documents.indexes.models.IndexerResyncOption] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = indexer.name # type: ignore - except AttributeError: - name = indexer - - # Create IndexerResyncBody from the list of options - resync_body = IndexerResyncBody(options=indexer_resync_options) - await self._client.indexers.resync(name, resync_body, **kwargs) - return - - @distributed_trace_async - async def get_indexer_status(self, name: str, **kwargs: Any) -> SearchIndexerStatus: - """Get the status of the indexer. - - :param name: The name of the indexer to fetch the status. - :type name: str - - :return: SearchIndexerStatus - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START get_indexer_status_async] - :end-before: [END get_indexer_status_async] - :language: python - :dedent: 4 - :caption: Get a SearchIndexer's status - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - return await self._client.indexers.get_status(name, **kwargs) - - @distributed_trace_async - async def create_data_source_connection( - self, data_source_connection: SearchIndexerDataSourceConnection, **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection. - - :param data_source_connection: The definition of the data source connection to create. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_data_source_operations_async.py - :start-after: [START create_data_source_connection_async] - :end-before: [END create_data_source_connection_async] - :language: python - :dedent: 4 - :caption: Create a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - # pylint:disable=protected-access - packed_data_source = data_source_connection._to_generated() - result = await self._client.data_sources.create(packed_data_source, **kwargs) - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace_async - async def create_or_update_data_source_connection( - self, - data_source_connection: SearchIndexerDataSourceConnection, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_connection: The definition of the data source connection to create or update. - :type data_source_connection: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :return: The created SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions( - data_source_connection, - match_condition, - ) - kwargs.update(access_condition) - name = data_source_connection.name - # pylint:disable=protected-access - packed_data_source = data_source_connection._to_generated() - result = await self._client.data_sources.create_or_update( - data_source_name=name, - data_source=packed_data_source, - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - **kwargs - ) - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace_async - async def delete_data_source_connection( - self, - data_source_connection: Union[str, SearchIndexerDataSourceConnection], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Deletes a data source connection. To use access conditions, the - SearchIndexerDataSourceConnection model must be provided instead of the name. - It is enough to provide the name of the data source connection to delete unconditionally - - :param data_source_connection: The data source connection to delete. - :type data_source_connection: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_data_source_operations_async.py - :start-after: [START delete_data_source_connection_async] - :end-before: [END delete_data_source_connection_async] - :language: python - :dedent: 4 - :caption: Delete a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions( - data_source_connection, - match_condition, - ) - kwargs.update(access_condition) - try: - name = data_source_connection.name # type: ignore - except AttributeError: - name = data_source_connection - await self._client.data_sources.delete(data_source_name=name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def get_data_source_connection( - self, name: str, *, select: Optional[List[str]] = None, **kwargs: Any - ) -> SearchIndexerDataSourceConnection: - """Retrieves a data source connection definition. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :param name: The name of the data source connection to retrieve. - :type name: str - :return: The SearchIndexerDataSourceConnection that is fetched. - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_data_source_operations_async.py - :start-after: [START get_data_source_connection_async] - :end-before: [END get_data_source_connection_async] - :language: python - :dedent: 4 - :caption: Retrieve a SearchIndexerDataSourceConnection - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.data_sources.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(result)) - - @distributed_trace_async - async def get_data_source_connections(self, **kwargs: Any) -> Sequence[SearchIndexerDataSourceConnection]: - """Lists all data source connections available for a search service. - - :return: List of all the data source connections. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_data_source_operations_async.py - :start-after: [START list_data_source_connection_async] - :end-before: [END list_data_source_connection_async] - :language: python - :dedent: 4 - :caption: List all SearchIndexerDataSourceConnections - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - # pylint:disable=protected-access - return [ - cast(SearchIndexerDataSourceConnection, SearchIndexerDataSourceConnection._from_generated(x)) - for x in result.data_sources - ] - - @distributed_trace_async - async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: - """Lists all data source connection names available for a search service. - - :return: List of all the data source connection names. - :rtype: list[str] - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.data_sources.list(**kwargs) - assert result.data_sources is not None # Hint for mypy - return [x.name for x in result.data_sources] - - @distributed_trace_async - async def get_skillsets(self, *, select: Optional[List[str]] = None, **kwargs) -> List[SearchIndexerSkillset]: - # pylint:disable=protected-access - """List the SearchIndexerSkillsets in an Azure Search service. - - :keyword select: Selects which top-level properties of the skillsets to retrieve. Specified as a - list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: list[str] - :return: List of SearchIndexerSkillsets - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - if select: - kwargs["select"] = ",".join(select) - result = await self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [ - cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(skillset)) - for skillset in result.skillsets - ] - - @distributed_trace_async - async def get_skillset_names(self, **kwargs) -> List[str]: - """List the SearchIndexerSkillset names in an Azure Search service. - - :return: List of SearchIndexerSkillset names - :rtype: list[str] - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.skillsets.list(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [x.name for x in result.skillsets] - - @distributed_trace_async - async def get_skillset(self, name: str, **kwargs) -> SearchIndexerSkillset: - """Retrieve a named SearchIndexerSkillset in an Azure Search service - - :param name: The name of the SearchIndexerSkillset to get - :type name: str - :return: The retrieved SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.ResourceNotFoundError: If the skillset doesn't exist. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = await self._client.skillsets.get(name, **kwargs) - # pylint:disable=protected-access - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace_async - async def delete_skillset( - self, - skillset: Union[str, SearchIndexerSkillset], - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any - ) -> None: - """Delete a named SearchIndexerSkillset in an Azure Search service. To use access conditions, - the SearchIndexerSkillset model must be provided instead of the name. It is enough to provide - the name of the skillset to delete unconditionally - - :param skillset: The SearchIndexerSkillset to delete - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - await self._client.skillsets.delete(name, error_map=error_map, **kwargs) - - @distributed_trace_async - async def create_skillset(self, skillset: SearchIndexerSkillset, **kwargs: Any) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service - - :param skillset: The SearchIndexerSkillset object to create - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :return: The created SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - result = await self._client.skillsets.create(skillset_gen, **kwargs) # type: ignore - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace_async - async def create_or_update_skillset( - self, - skillset: SearchIndexerSkillset, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - **kwargs: Any - ) -> SearchIndexerSkillset: - # pylint:disable=protected-access - """Create a new SearchIndexerSkillset in an Azure Search service, or update an - existing one. - - :param skillset: The SearchIndexerSkillset object to create or update - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. - :paramtype disable_cache_reprocessing_change_detection: bool - :return: The created or updated SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - error_map, access_condition = get_access_conditions(skillset, match_condition) - kwargs.update(access_condition) - skillset_gen = skillset._to_generated() if hasattr(skillset, "_to_generated") else skillset - - result = await self._client.skillsets.create_or_update( - skillset_name=skillset.name, - skillset=skillset_gen, # type: ignore - prefer="return=representation", - error_map=error_map, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs - ) - return cast(SearchIndexerSkillset, SearchIndexerSkillset._from_generated(result)) - - @distributed_trace_async - async def reset_skills(self, skillset: Union[str, SearchIndexerSkillset], skill_names: List[str], **kwargs) -> None: - """Reset an existing skillset in a search service. - - :param skillset: The SearchIndexerSkillset to reset - :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset - :param skill_names: the names of skills to be reset. - :type skill_names: List[str] - :return: None, or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. - """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - try: - name = skillset.name # type: ignore - except AttributeError: - name = skillset - names = SkillNames(skill_names=skill_names) - await self._client.skillsets.reset_skills(skillset_name=name, skill_names=names, **kwargs) - return diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py new file mode 100644 index 000000000000..6b1532241601 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataSourcesOperations # type: ignore +from ._operations import IndexersOperations # type: ignore +from ._operations import SkillsetsOperations # type: ignore +from ._operations import SynonymMapsOperations # type: ignore +from ._operations import IndexesOperations # type: ignore +from ._operations import AliasesOperations # type: ignore +from ._operations import AgentsOperations # type: ignore +from ._operations import SourcesOperations # type: ignore +from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataSourcesOperations", + "IndexersOperations", + "SkillsetsOperations", + "SynonymMapsOperations", + "IndexesOperations", + "AliasesOperations", + "AgentsOperations", + "SourcesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py new file mode 100644 index 000000000000..15073ee0c257 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py @@ -0,0 +1,5495 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import AsyncPipelineClient, MatchConditions +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceModifiedError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2 +from .... import models as _models3 +from ...._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ...._utils.serialization import Deserializer, Serializer +from ...._utils.utils import ClientMixinABC +from ...._validation import api_version_validation +from ...operations._operations import ( + build_agents_create_or_update_request, + build_agents_create_request, + build_agents_delete_request, + build_agents_get_request, + build_agents_list_request, + build_aliases_create_or_update_request, + build_aliases_create_request, + build_aliases_delete_request, + build_aliases_get_request, + build_aliases_list_request, + build_data_sources_create_or_update_request, + build_data_sources_create_request, + build_data_sources_delete_request, + build_data_sources_get_request, + build_data_sources_list_request, + build_indexers_create_or_update_request, + build_indexers_create_request, + build_indexers_delete_request, + build_indexers_get_request, + build_indexers_get_status_request, + build_indexers_list_request, + build_indexers_reset_docs_request, + build_indexers_reset_request, + build_indexers_resync_request, + build_indexers_run_request, + build_indexes_analyze_request, + build_indexes_create_or_update_request, + build_indexes_create_request, + build_indexes_delete_request, + build_indexes_get_request, + build_indexes_get_statistics_request, + build_indexes_list_request, + build_search_index_get_index_stats_summary_request, + build_search_index_get_service_statistics_request, + build_skillsets_create_or_update_request, + build_skillsets_create_request, + build_skillsets_delete_request, + build_skillsets_get_request, + build_skillsets_list_request, + build_skillsets_reset_skills_request, + build_sources_create_or_update_request, + build_sources_create_request, + build_sources_delete_request, + build_sources_get_request, + build_sources_list_request, + build_synonym_maps_create_or_update_request, + build_synonym_maps_create_request, + build_synonym_maps_delete_request, + build_synonym_maps_get_request, + build_synonym_maps_list_request, +) +from .._configuration import SearchIndexClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class DataSourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`data_sources` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + data_source_name: str, + data_source: _models2.SearchIndexerDataSource, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + data_source_name: str, + data_source: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + data_source_name: str, + data_source: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update( + self, + data_source_name: str, + data_source: Union[_models2.SearchIndexerDataSource, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Is one of the + following types: SearchIndexerDataSource, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or + IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerDataSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source, (IOBase, bytes)): + _content = data_source + else: + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_data_sources_create_or_update_request( + data_source_name=data_source_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerDataSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete( + self, + data_source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a datasource. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_data_sources_delete_request( + data_source_name=data_source_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get(self, data_source_name: str, **kwargs: Any) -> _models2.SearchIndexerDataSource: + """Retrieves a datasource definition. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerDataSource] = kwargs.pop("cls", None) + + _request = build_data_sources_get_request( + data_source_name=data_source_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerDataSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListDataSourcesResult: + """Lists all datasources available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.ListDataSourcesResult] = kwargs.pop("cls", None) + + _request = build_data_sources_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.ListDataSourcesResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, data_source: _models2.SearchIndexerDataSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, data_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, data_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, data_source: Union[_models2.SearchIndexerDataSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Is one of the following types: + SearchIndexerDataSource, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or + IO[bytes] + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerDataSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source, (IOBase, bytes)): + _content = data_source + else: + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_data_sources_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerDataSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class IndexersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`indexers` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def reset(self, indexer_name: str, **kwargs: Any) -> None: + """Resets the change tracking state associated with an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_reset_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def resync(self, indexer_name: str, **kwargs: Any) -> None: + """Resync selective options from the datasource to be re-ingested by the indexer.". + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_resync_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[_models2.DocumentKeysOrIds] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[JSON] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: JSON + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[IO[bytes]] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[Union[_models2.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + *, + overwrite: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, + IO[bytes] Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or + IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if keys_or_ids else None + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if keys_or_ids else None + _content = None + if isinstance(keys_or_ids, (IOBase, bytes)): + _content = keys_or_ids + else: + if keys_or_ids is not None: + _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + else: + _content = None + + _request = build_indexers_reset_docs_request( + indexer_name=indexer_name, + overwrite=overwrite, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def run(self, indexer_name: str, **kwargs: Any) -> None: + """Runs an indexer on-demand. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_run_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, + indexer_name: str, + indexer: _models2.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + indexer_name: str, + indexer: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + indexer_name: str, + indexer: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + params_added_on={ + "2025-08-01-preview": [ + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", + ] + }, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update( + self, + indexer_name: str, + indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Is one of the following + types: SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexers_create_or_update_request( + indexer_name=indexer_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete( + self, + indexer_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_delete_request( + indexer_name=indexer_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexer: + """Retrieves an indexer definition. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + _request = build_indexers_get_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListIndexersResult: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListIndexersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.ListIndexersResult] = kwargs.pop("cls", None) + + _request = build_indexers_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.ListIndexersResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, indexer: _models2.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Is one of the following types: + SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexers_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_status(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexerStatus: + """Returns the current status and execution history of an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerStatus] = kwargs.pop("cls", None) + + _request = build_indexers_get_status_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SkillsetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`skillsets` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + skillset_name: str, + skillset: _models2.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + skillset_name: str, + skillset: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + skillset_name: str, + skillset: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + params_added_on={ + "2025-08-01-preview": [ + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", + ] + }, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update( + self, + skillset_name: str, + skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_skillsets_create_or_update_request( + skillset_name=skillset_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete( + self, + skillset_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_skillsets_delete_request( + skillset_name=skillset_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get(self, skillset_name: str, **kwargs: Any) -> _models2.SearchIndexerSkillset: + """Retrieves a skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + + _request = build_skillsets_get_request( + skillset_name=skillset_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSkillsetsResult: + """List all skillsets in a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.ListSkillsetsResult] = kwargs.pop("cls", None) + + _request = build_skillsets_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.ListSkillsetsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, skillset: _models2.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. Is + one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_skillsets_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def reset_skills( + self, + skillset_name: str, + skill_names: _models2.SkillNames, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def reset_skills( + self, skillset_name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def reset_skills( + self, skillset_name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def reset_skills( + self, skillset_name: str, skill_names: Union[_models2.SkillNames, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skill_names, (IOBase, bytes)): + _content = skill_names + else: + _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_skillsets_reset_skills_request( + skillset_name=skillset_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class SynonymMapsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`synonym_maps` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + synonym_map_name: str, + synonym_map: _models2.SynonymMap, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + synonym_map_name: str, + synonym_map: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + synonym_map_name: str, + synonym_map: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + synonym_map_name: str, + synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Is one of the + following types: SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_synonym_maps_create_or_update_request( + synonym_map_name=synonym_map_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete( + self, + synonym_map_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a synonym map. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_synonym_maps_delete_request( + synonym_map_name=synonym_map_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get(self, synonym_map_name: str, **kwargs: Any) -> _models2.SynonymMap: + """Retrieves a synonym map definition. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + + _request = build_synonym_maps_get_request( + synonym_map_name=synonym_map_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSynonymMapsResult: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.ListSynonymMapsResult] = kwargs.pop("cls", None) + + _request = build_synonym_maps_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.ListSynonymMapsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, synonym_map: _models2.SynonymMap, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Is one of the following types: + SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_synonym_maps_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class IndexesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`indexes` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + index_name: str, + index: _models2.SearchIndex, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + index_name: str, + index: JSON, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: JSON + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + index_name: str, + index: IO[bytes], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + index_name: str, + index: Union[_models2.SearchIndex, JSON, IO[bytes]], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_create_or_update_request( + index_name=index_name, + allow_index_downtime=allow_index_downtime, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete( + self, + index_name: str, + *, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search index and all the documents it contains. This operation is permanent, with no + recovery option. Make sure you have a master copy of your index definition, data ingestion + code, and a backup of the primary data source in case you need to re-build the index. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexes_delete_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models2.SearchIndex: + """Retrieves an index definition. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + _request = build_indexes_get_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SearchIndex"]: + """Lists all indexes available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: An iterator like instance of SearchIndex + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models2.SearchIndex]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_indexes_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models2.SearchIndex], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create( + self, index: _models2.SearchIndex, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, index: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create(self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kwargs: Any) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_statistics( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models2.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.GetIndexStatisticsResult] = kwargs.pop("cls", None) + + _request = build_indexes_get_statistics_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.GetIndexStatisticsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def analyze( + self, + index_name: str, + request: _models2.AnalyzeRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def analyze( + self, + index_name: str, + request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def analyze( + self, + index_name: str, + request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def analyze( + self, + index_name: str, + request: Union[_models2.AnalyzeRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Is one of the following + types: AnalyzeRequest, JSON, IO[bytes] Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.AnalyzeResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_analyze_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.AnalyzeResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class AliasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`aliases` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + alias_name: str, + alias: _models2.SearchAlias, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + alias_name: str, + alias: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + alias_name: str, + alias: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": [ + "api_version", + "prefer", + "client_request_id", + "alias_name", + "content_type", + "accept", + "etag", + "match_condition", + ] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update( + self, + alias_name: str, + alias: Union[_models2.SearchAlias, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_aliases_create_or_update_request( + alias_name=alias_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "etag", "match_condition"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def delete( + self, + alias_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_aliases_delete_request( + alias_name=alias_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def get(self, alias_name: str, **kwargs: Any) -> _models2.SearchAlias: + """Retrieves an alias definition. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + + _request = build_aliases_get_request( + alias_name=alias_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def list(self, **kwargs: Any) -> AsyncItemPaged["_models2.SearchAlias"]: + """Lists all aliases available for a search service. + + :return: An iterator like instance of SearchAlias + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models2.SearchAlias]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_aliases_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models2.SearchAlias], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create( + self, alias: _models2.SearchAlias, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def create(self, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], **kwargs: Any) -> _models2.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_aliases_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class AgentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`agents` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + agent_name: str, + knowledge_agent: _models2.KnowledgeAgent, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + agent_name: str, + knowledge_agent: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + agent_name: str, + knowledge_agent: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": [ + "api_version", + "prefer", + "client_request_id", + "agent_name", + "content_type", + "accept", + "etag", + "match_condition", + ] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update( + self, + agent_name: str, + knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Is one of the + following types: KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or + IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent + else: + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agents_create_or_update_request( + agent_name=agent_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "etag", "match_condition"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def delete( + self, + agent_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_agents_delete_request( + agent_name=agent_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def get(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: + """Retrieves an agent definition. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + + _request = build_agents_get_request( + agent_name=agent_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def list(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: + """Lists all agents available for a search service. + + :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) + + _request = build_agents_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.ListKnowledgeAgentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, knowledge_agent: _models2.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def create( + self, knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Is one of the following types: + KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or + IO[bytes] + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent + else: + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agents_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.SearchIndexClient`'s + :attr:`sources` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + source_name: str, + knowledge_source: _models2.KnowledgeSource, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + source_name: str, + knowledge_source: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + source_name: str, + knowledge_source: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": [ + "api_version", + "prefer", + "client_request_id", + "source_name", + "content_type", + "accept", + "etag", + "match_condition", + ] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update( + self, + source_name: str, + knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Is one of + the following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_sources_create_or_update_request( + source_name=source_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "client_request_id", "source_name", "etag", "match_condition"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def delete( + self, + source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes an existing knowledge source. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_sources_delete_request( + source_name=source_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "source_name", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def get(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource: + """Retrieves a knowledge source definition. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + + _request = build_sources_get_request( + source_name=source_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def list(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: + """Lists all knowledge sources available for a search service. + + :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) + + _request = build_sources_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.ListKnowledgeSourcesResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, knowledge_source: _models2.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def create( + self, knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Is one of the + following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_sources_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class _SearchIndexClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchIndexClientConfiguration] +): + + @distributed_trace_async + async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceStatistics: + """Gets service level statistics for a search service. + + :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchServiceStatistics] = kwargs.pop("cls", None) + + _request = build_search_index_get_service_statistics_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchServiceStatistics, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: + """Retrieves a summary of statistics for all indexes in the search service. + + :return: An iterator like instance of IndexStatisticsSummary + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models2.IndexStatisticsSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_get_index_stats_summary_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models2.IndexStatisticsSummary], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py index 7340e4ec6214..aa58ae78fc31 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py @@ -1,86 +1,59 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._index import ( - ComplexField, - SearchField, - SearchableField, - SimpleField, - SearchIndex, -) -from . import _edm -from ..._generated.models import SuggestOptions -from .._generated.models import ( - SearchAlias, +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore AIServicesAccountIdentity, AIServicesAccountKey, AIServicesVisionParameters, AIServicesVisionVectorizer, - AIFoundryModelCatalogName, - AzureMachineLearningParameters, - AzureMachineLearningSkill, - AzureMachineLearningVectorizer, + AnalyzeRequest, AnalyzeResult, AnalyzedTokenInfo, AsciiFoldingTokenFilter, + AzureActiveDirectoryApplicationCredentials, AzureBlobKnowledgeSource, AzureBlobKnowledgeSourceParameters, + AzureMachineLearningParameters, + AzureMachineLearningSkill, + AzureMachineLearningVectorizer, AzureOpenAIEmbeddingSkill, AzureOpenAITokenizerParameters, - AzureOpenAIModelName, - AzureOpenAIVectorizerParameters, AzureOpenAIVectorizer, - BinaryQuantizationCompression, - BlobIndexerDataToExtract, - BlobIndexerImageAction, - BlobIndexerParsingMode, - BlobIndexerPDFTextRotationAlgorithm, + AzureOpenAIVectorizerParameters, + AzureOpenAiParameters, BM25SimilarityAlgorithm, + BinaryQuantizationCompression, CharFilter, - CharFilterName, - ChatCompletionExtraParametersBehavior, + ChatCompletionCommonModelParameters, ChatCompletionResponseFormat, - ChatCompletionResponseFormatJsonSchemaProperties, - ChatCompletionResponseFormatType, ChatCompletionSchema, + ChatCompletionSchemaProperties, ChatCompletionSkill, CjkBigramTokenFilter, - CjkBigramTokenFilterScripts, ClassicSimilarityAlgorithm, ClassicTokenizer, CognitiveServicesAccount, CognitiveServicesAccountKey, CommonGramTokenFilter, - CommonModelParameters, ConditionalSkill, CorsOptions, + CreatedResources, + CustomAnalyzer, CustomEntity, CustomEntityAlias, CustomEntityLookupSkill, - CustomEntityLookupSkillLanguage, CustomNormalizer, DataChangeDetectionPolicy, DataDeletionDetectionPolicy, @@ -92,19 +65,13 @@ DocumentExtractionSkill, DocumentIntelligenceLayoutSkill, DocumentIntelligenceLayoutSkillChunkingProperties, - DocumentIntelligenceLayoutSkillChunkingUnit, - DocumentIntelligenceLayoutSkillExtractionOptions, - DocumentIntelligenceLayoutSkillMarkdownHeaderDepth, - DocumentIntelligenceLayoutSkillOutputFormat, - DocumentIntelligenceLayoutSkillOutputMode, DocumentKeysOrIds, EdgeNGramTokenFilter, EdgeNGramTokenizer, - EdgeNGramTokenFilterSide, ElisionTokenFilter, - EntityCategory, EntityLinkingSkill, - EntityRecognitionSkillLanguage, + EntityRecognitionSkill, + EntityRecognitionSkillV3, ExhaustiveKnnAlgorithmConfiguration, ExhaustiveKnnParameters, FieldMapping, @@ -113,96 +80,79 @@ FreshnessScoringParameters, GetIndexStatisticsResult, HighWaterMarkChangeDetectionPolicy, - HnswParameters, HnswAlgorithmConfiguration, + HnswParameters, ImageAnalysisSkill, - ImageAnalysisSkillLanguage, - ImageDetail, + IndexStatisticsSummary, IndexerCurrentState, - IndexerExecutionEnvironment, IndexerExecutionResult, IndexerResyncBody, - IndexerExecutionStatus, - IndexerPermissionOption, - IndexerResyncOption, - IndexerStatus, - IndexingMode, IndexingParameters, IndexingParametersConfiguration, IndexingSchedule, - IndexProjectionMode, - IndexStatisticsSummary, InputFieldMappingEntry, KeepTokenFilter, KeyPhraseExtractionSkill, - KeyPhraseExtractionSkillLanguage, KeywordMarkerTokenFilter, - KeywordTokenizerV2, + KeywordTokenizer, KnowledgeAgent, - KnowledgeAgentAzureOpenAIModel, + KnowledgeAgentAzureOpenAiModel, KnowledgeAgentModel, KnowledgeAgentOutputConfiguration, - KnowledgeAgentModelKind, - KnowledgeAgentOutputConfigurationModality, KnowledgeAgentRequestLimits, KnowledgeSource, - KnowledgeSourceKind, KnowledgeSourceReference, LanguageDetectionSkill, LengthTokenFilter, LexicalAnalyzer, LexicalNormalizer, - LexicalNormalizerName, - LexicalAnalyzerName, LexicalTokenizer, - LexicalTokenizerName, LimitTokenFilter, + ListDataSourcesResult, + ListIndexersResult, + ListKnowledgeAgentsResult, + ListKnowledgeSourcesResult, + ListSkillsetsResult, + ListSynonymMapsResult, LuceneStandardAnalyzer, LuceneStandardTokenizer, MagnitudeScoringFunction, MagnitudeScoringParameters, - MarkdownHeaderDepth, - MarkdownParsingSubmode, MappingCharFilter, MergeSkill, MicrosoftLanguageStemmingTokenizer, MicrosoftLanguageTokenizer, - MicrosoftStemmingTokenizerLanguage, - MicrosoftTokenizerLanguage, - NativeBlobSoftDeleteDeletionDetectionPolicy, NGramTokenFilter, NGramTokenizer, - OcrLineEnding, + NativeBlobSoftDeleteDeletionDetectionPolicy, OcrSkill, - OcrSkillLanguage, OutputFieldMappingEntry, - PathHierarchyTokenizerV2, + PIIDetectionSkill, + PathHierarchyTokenizer, + PatternAnalyzer, PatternCaptureTokenFilter, PatternReplaceCharFilter, PatternReplaceTokenFilter, - PhoneticEncoder, + PatternTokenizer, PhoneticTokenFilter, - PIIDetectionSkill, - PIIDetectionSkillMaskingMode, - PermissionFilter, - RankingOrder, - RegexFlags, RescoringOptions, ResourceCounter, ScalarQuantizationCompression, ScalarQuantizationParameters, ScoringFunction, - ScoringFunctionAggregation, - ScoringFunctionInterpolation, ScoringProfile, + SearchAlias, + SearchField, + SearchIndex, SearchIndexKnowledgeSource, SearchIndexKnowledgeSourceParameters, + SearchIndexer, SearchIndexerCache, SearchIndexerDataContainer, SearchIndexerDataIdentity, SearchIndexerDataNoneIdentity, + SearchIndexerDataSource, SearchIndexerDataUserAssignedIdentity, - SearchIndexerDataSourceType, SearchIndexerError, SearchIndexerIndexProjection, SearchIndexerIndexProjectionSelector, @@ -211,14 +161,16 @@ SearchIndexerKnowledgeStoreBlobProjectionSelector, SearchIndexerKnowledgeStoreFileProjectionSelector, SearchIndexerKnowledgeStoreObjectProjectionSelector, + SearchIndexerKnowledgeStoreParameters, SearchIndexerKnowledgeStoreProjection, SearchIndexerKnowledgeStoreProjectionSelector, SearchIndexerKnowledgeStoreTableProjectionSelector, SearchIndexerLimits, SearchIndexerSkill, + SearchIndexerSkillset, SearchIndexerStatus, SearchIndexerWarning, - SearchIndexPermissionFilterOption, + SearchResourceEncryptionKey, SearchServiceCounters, SearchServiceLimits, SearchServiceStatistics, @@ -227,136 +179,161 @@ SemanticField, SemanticPrioritizedFields, SemanticSearch, - SentimentSkillLanguage, + SentimentSkill, + SentimentSkillV3, ShaperSkill, ShingleTokenFilter, SimilarityAlgorithm, SkillNames, SnowballTokenFilter, - SnowballTokenFilterLanguage, SoftDeleteColumnDeletionDetectionPolicy, - SplitSkillEncoderModelName, SplitSkill, - SplitSkillLanguage, - SplitSkillUnit, SqlIntegratedChangeTrackingPolicy, StemmerOverrideTokenFilter, StemmerTokenFilter, - StemmerTokenFilterLanguage, StopAnalyzer, - StopwordsList, StopwordsTokenFilter, + SynonymMap, SynonymTokenFilter, TagScoringFunction, TagScoringParameters, - TextSplitMode, TextTranslationSkill, - TextTranslationSkillLanguage, TextWeights, - TokenCharacterKind, TokenFilter, - TokenFilterName, TruncateTokenFilter, UaxUrlEmailTokenizer, UniqueTokenFilter, - VectorEncodingFormat, VectorSearch, VectorSearchAlgorithmConfiguration, - VectorSearchAlgorithmKind, - VectorSearchAlgorithmMetric, VectorSearchCompression, - VectorSearchCompressionKind, - VectorSearchCompressionRescoreStorageMethod, - VectorSearchCompressionTarget, VectorSearchProfile, VectorSearchVectorizer, - VectorSearchVectorizerKind, - VisualFeature, VisionVectorizeSkill, + WebApiHttpHeaders, WebApiSkill, WebApiVectorizer, WebApiVectorizerParameters, WordDelimiterTokenFilter, ) -from ._models import ( - AnalyzeTextOptions, - CustomAnalyzer, - EntityRecognitionSkill, - EntityRecognitionSkillVersion, - PatternAnalyzer, - PatternTokenizer, - SearchIndexer, - SearchIndexerDataSourceConnection, - SearchIndexerSkillset, - SearchResourceEncryptionKey, - SentimentSkill, - SentimentSkillVersion, - SynonymMap, -) - -SearchFieldDataType = _edm - - -class KeywordTokenizer(KeywordTokenizerV2): - pass - - -class PathHierarchyTokenizer(PathHierarchyTokenizerV2): - pass +from ._enums import ( # type: ignore + AIFoundryModelCatalogName, + AzureOpenAIModelName, + BlobIndexerDataToExtract, + BlobIndexerImageAction, + BlobIndexerPDFTextRotationAlgorithm, + BlobIndexerParsingMode, + CharFilterName, + ChatCompletionExtraParametersBehavior, + ChatCompletionResponseFormatType, + CjkBigramTokenFilterScripts, + CustomEntityLookupSkillLanguage, + DocumentIntelligenceLayoutSkillChunkingUnit, + DocumentIntelligenceLayoutSkillExtractionOptions, + DocumentIntelligenceLayoutSkillMarkdownHeaderDepth, + DocumentIntelligenceLayoutSkillOutputFormat, + DocumentIntelligenceLayoutSkillOutputMode, + EdgeNGramTokenFilterSide, + EntityCategory, + EntityRecognitionSkillLanguage, + ImageAnalysisSkillLanguage, + ImageDetail, + IndexProjectionMode, + IndexerExecutionEnvironment, + IndexerExecutionStatus, + IndexerExecutionStatusDetail, + IndexerPermissionOption, + IndexerResyncOption, + IndexerStatus, + IndexingMode, + KeyPhraseExtractionSkillLanguage, + KnowledgeAgentModelKind, + KnowledgeAgentOutputConfigurationModality, + KnowledgeSourceKind, + LexicalAnalyzerName, + LexicalNormalizerName, + LexicalTokenizerName, + MarkdownHeaderDepth, + MarkdownParsingSubmode, + MicrosoftStemmingTokenizerLanguage, + MicrosoftTokenizerLanguage, + OcrLineEnding, + OcrSkillLanguage, + PIIDetectionSkillMaskingMode, + PermissionFilter, + PhoneticEncoder, + RankingOrder, + RegexFlags, + ScoringFunctionAggregation, + ScoringFunctionInterpolation, + SearchFieldDataType, + SearchIndexPermissionFilterOption, + SearchIndexerDataSourceType, + SentimentSkillLanguage, + SnowballTokenFilterLanguage, + SplitSkillEncoderModelName, + SplitSkillLanguage, + SplitSkillUnit, + StemmerTokenFilterLanguage, + StopwordsList, + TextSplitMode, + TextTranslationSkillLanguage, + TokenCharacterKind, + TokenFilterName, + VectorEncodingFormat, + VectorSearchAlgorithmKind, + VectorSearchAlgorithmMetric, + VectorSearchCompressionKind, + VectorSearchCompressionRescoreStorageMethod, + VectorSearchCompressionTarget, + VectorSearchVectorizerKind, + VisualFeature, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk -__all__ = ( +__all__ = [ "AIServicesAccountIdentity", "AIServicesAccountKey", "AIServicesVisionParameters", "AIServicesVisionVectorizer", - "AIFoundryModelCatalogName", - "AnalyzeTextOptions", + "AnalyzeRequest", "AnalyzeResult", "AnalyzedTokenInfo", "AsciiFoldingTokenFilter", - "AzureOpenAIEmbeddingSkill", - "AzureOpenAITokenizerParameters", - "AzureOpenAIModelName", - "AzureOpenAIVectorizerParameters", - "AzureOpenAIVectorizer", + "AzureActiveDirectoryApplicationCredentials", "AzureBlobKnowledgeSource", "AzureBlobKnowledgeSourceParameters", "AzureMachineLearningParameters", "AzureMachineLearningSkill", "AzureMachineLearningVectorizer", - "BinaryQuantizationCompression", - "BlobIndexerDataToExtract", - "BlobIndexerImageAction", - "BlobIndexerParsingMode", - "BlobIndexerPDFTextRotationAlgorithm", + "AzureOpenAIEmbeddingSkill", + "AzureOpenAITokenizerParameters", + "AzureOpenAIVectorizer", + "AzureOpenAIVectorizerParameters", + "AzureOpenAiParameters", "BM25SimilarityAlgorithm", + "BinaryQuantizationCompression", "CharFilter", - "CharFilterName", - "ChatCompletionExtraParametersBehavior", + "ChatCompletionCommonModelParameters", "ChatCompletionResponseFormat", - "ChatCompletionResponseFormatType", - "ChatCompletionResponseFormatJsonSchemaProperties", "ChatCompletionSchema", + "ChatCompletionSchemaProperties", "ChatCompletionSkill", "CjkBigramTokenFilter", - "CjkBigramTokenFilterScripts", "ClassicSimilarityAlgorithm", "ClassicTokenizer", "CognitiveServicesAccount", "CognitiveServicesAccountKey", "CommonGramTokenFilter", - "CommonModelParameters", - "ComplexField", "ConditionalSkill", "CorsOptions", + "CreatedResources", "CustomAnalyzer", "CustomEntity", "CustomEntityAlias", "CustomEntityLookupSkill", - "WebApiVectorizer", - "WebApiVectorizerParameters", - "CustomEntityLookupSkillLanguage", "CustomNormalizer", "DataChangeDetectionPolicy", "DataDeletionDetectionPolicy", @@ -368,21 +345,13 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "DocumentExtractionSkill", "DocumentIntelligenceLayoutSkill", "DocumentIntelligenceLayoutSkillChunkingProperties", - "DocumentIntelligenceLayoutSkillChunkingUnit", - "DocumentIntelligenceLayoutSkillExtractionOptions", - "DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", - "DocumentIntelligenceLayoutSkillOutputFormat", - "DocumentIntelligenceLayoutSkillOutputMode", "DocumentKeysOrIds", "EdgeNGramTokenFilter", "EdgeNGramTokenizer", "ElisionTokenFilter", - "EdgeNGramTokenFilterSide", - "EntityCategory", "EntityLinkingSkill", "EntityRecognitionSkill", - "EntityRecognitionSkillLanguage", - "EntityRecognitionSkillVersion", + "EntityRecognitionSkillV3", "ExhaustiveKnnAlgorithmConfiguration", "ExhaustiveKnnParameters", "FieldMapping", @@ -391,92 +360,68 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "FreshnessScoringParameters", "GetIndexStatisticsResult", "HighWaterMarkChangeDetectionPolicy", - "HnswParameters", "HnswAlgorithmConfiguration", + "HnswParameters", "ImageAnalysisSkill", - "ImageAnalysisSkillLanguage", - "ImageDetail", + "IndexStatisticsSummary", "IndexerCurrentState", - "IndexerExecutionEnvironment", "IndexerExecutionResult", "IndexerResyncBody", - "IndexerExecutionStatus", - "IndexerPermissionOption", - "IndexerResyncOption", - "IndexerStatus", - "IndexingMode", "IndexingParameters", "IndexingParametersConfiguration", "IndexingSchedule", - "IndexProjectionMode", "InputFieldMappingEntry", "KeepTokenFilter", "KeyPhraseExtractionSkill", - "KeyPhraseExtractionSkillLanguage", "KeywordMarkerTokenFilter", "KeywordTokenizer", - "LanguageDetectionSkill", "KnowledgeAgent", - "KnowledgeAgentAzureOpenAIModel", + "KnowledgeAgentAzureOpenAiModel", "KnowledgeAgentModel", - "KnowledgeAgentModelKind", "KnowledgeAgentOutputConfiguration", - "KnowledgeAgentOutputConfigurationModality", "KnowledgeAgentRequestLimits", "KnowledgeSource", - "KnowledgeSourceKind", "KnowledgeSourceReference", + "LanguageDetectionSkill", "LengthTokenFilter", "LexicalAnalyzer", - "LexicalAnalyzerName", "LexicalNormalizer", - "LexicalNormalizerName", "LexicalTokenizer", - "LexicalTokenizerName", "LimitTokenFilter", - "IndexStatisticsSummary", + "ListDataSourcesResult", + "ListIndexersResult", + "ListKnowledgeAgentsResult", + "ListKnowledgeSourcesResult", + "ListSkillsetsResult", + "ListSynonymMapsResult", "LuceneStandardAnalyzer", "LuceneStandardTokenizer", "MagnitudeScoringFunction", "MagnitudeScoringParameters", - "MarkdownHeaderDepth", - "MarkdownParsingSubmode", "MappingCharFilter", "MergeSkill", "MicrosoftLanguageStemmingTokenizer", "MicrosoftLanguageTokenizer", - "MicrosoftStemmingTokenizerLanguage", - "MicrosoftTokenizerLanguage", - "NativeBlobSoftDeleteDeletionDetectionPolicy", "NGramTokenFilter", "NGramTokenizer", - "OcrLineEnding", + "NativeBlobSoftDeleteDeletionDetectionPolicy", "OcrSkill", - "OcrSkillLanguage", "OutputFieldMappingEntry", + "PIIDetectionSkill", "PathHierarchyTokenizer", "PatternAnalyzer", "PatternCaptureTokenFilter", "PatternReplaceCharFilter", "PatternReplaceTokenFilter", "PatternTokenizer", - "PermissionFilter", - "PIIDetectionSkill", - "PIIDetectionSkillMaskingMode", - "PhoneticEncoder", "PhoneticTokenFilter", - "RankingOrder", - "RegexFlags", "RescoringOptions", "ResourceCounter", "ScalarQuantizationCompression", "ScalarQuantizationParameters", "ScoringFunction", - "ScoringFunctionAggregation", - "ScoringFunctionInterpolation", "ScoringProfile", "SearchAlias", - "SearchableField", "SearchField", "SearchIndex", "SearchIndexKnowledgeSource", @@ -486,9 +431,8 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SearchIndexerDataContainer", "SearchIndexerDataIdentity", "SearchIndexerDataNoneIdentity", + "SearchIndexerDataSource", "SearchIndexerDataUserAssignedIdentity", - "SearchIndexerDataSourceConnection", - "SearchIndexerDataSourceType", "SearchIndexerError", "SearchIndexerIndexProjection", "SearchIndexerIndexProjectionSelector", @@ -497,6 +441,7 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SearchIndexerKnowledgeStoreBlobProjectionSelector", "SearchIndexerKnowledgeStoreFileProjectionSelector", "SearchIndexerKnowledgeStoreObjectProjectionSelector", + "SearchIndexerKnowledgeStoreParameters", "SearchIndexerKnowledgeStoreProjection", "SearchIndexerKnowledgeStoreProjectionSelector", "SearchIndexerKnowledgeStoreTableProjectionSelector", @@ -505,7 +450,6 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SearchIndexerSkillset", "SearchIndexerStatus", "SearchIndexerWarning", - "SearchIndexPermissionFilterOption", "SearchResourceEncryptionKey", "SearchServiceCounters", "SearchServiceLimits", @@ -516,57 +460,111 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "SemanticPrioritizedFields", "SemanticSearch", "SentimentSkill", - "SentimentSkillLanguage", - "SentimentSkillVersion", + "SentimentSkillV3", "ShaperSkill", "ShingleTokenFilter", - "SimpleField", "SimilarityAlgorithm", "SkillNames", "SnowballTokenFilter", - "SnowballTokenFilterLanguage", - "SplitSkillEncoderModelName", "SoftDeleteColumnDeletionDetectionPolicy", "SplitSkill", - "SplitSkillLanguage", - "SplitSkillUnit", "SqlIntegratedChangeTrackingPolicy", "StemmerOverrideTokenFilter", "StemmerTokenFilter", - "StemmerTokenFilterLanguage", "StopAnalyzer", - "StopwordsList", "StopwordsTokenFilter", - "SuggestOptions", "SynonymMap", "SynonymTokenFilter", "TagScoringFunction", "TagScoringParameters", - "TextSplitMode", "TextTranslationSkill", - "TextTranslationSkillLanguage", "TextWeights", - "TokenCharacterKind", "TokenFilter", - "TokenFilterName", "TruncateTokenFilter", "UaxUrlEmailTokenizer", "UniqueTokenFilter", - "VectorEncodingFormat", "VectorSearch", "VectorSearchAlgorithmConfiguration", - "VectorSearchAlgorithmKind", - "VectorSearchAlgorithmMetric", "VectorSearchCompression", - "VectorSearchCompressionKind", - "VectorSearchCompressionRescoreStorageMethod", - "VectorSearchCompressionTarget", "VectorSearchProfile", "VectorSearchVectorizer", - "VectorSearchVectorizerKind", - "VisualFeature", "VisionVectorizeSkill", + "WebApiHttpHeaders", "WebApiSkill", + "WebApiVectorizer", + "WebApiVectorizerParameters", "WordDelimiterTokenFilter", + "AIFoundryModelCatalogName", + "AzureOpenAIModelName", + "BlobIndexerDataToExtract", + "BlobIndexerImageAction", + "BlobIndexerPDFTextRotationAlgorithm", + "BlobIndexerParsingMode", + "CharFilterName", + "ChatCompletionExtraParametersBehavior", + "ChatCompletionResponseFormatType", + "CjkBigramTokenFilterScripts", + "CustomEntityLookupSkillLanguage", + "DocumentIntelligenceLayoutSkillChunkingUnit", + "DocumentIntelligenceLayoutSkillExtractionOptions", + "DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", + "DocumentIntelligenceLayoutSkillOutputFormat", + "DocumentIntelligenceLayoutSkillOutputMode", + "EdgeNGramTokenFilterSide", + "EntityCategory", + "EntityRecognitionSkillLanguage", + "ImageAnalysisSkillLanguage", + "ImageDetail", + "IndexProjectionMode", + "IndexerExecutionEnvironment", + "IndexerExecutionStatus", + "IndexerExecutionStatusDetail", + "IndexerPermissionOption", + "IndexerResyncOption", + "IndexerStatus", + "IndexingMode", + "KeyPhraseExtractionSkillLanguage", + "KnowledgeAgentModelKind", + "KnowledgeAgentOutputConfigurationModality", + "KnowledgeSourceKind", + "LexicalAnalyzerName", + "LexicalNormalizerName", + "LexicalTokenizerName", + "MarkdownHeaderDepth", + "MarkdownParsingSubmode", + "MicrosoftStemmingTokenizerLanguage", + "MicrosoftTokenizerLanguage", + "OcrLineEnding", + "OcrSkillLanguage", + "PIIDetectionSkillMaskingMode", + "PermissionFilter", + "PhoneticEncoder", + "RankingOrder", + "RegexFlags", + "ScoringFunctionAggregation", + "ScoringFunctionInterpolation", "SearchFieldDataType", -) + "SearchIndexPermissionFilterOption", + "SearchIndexerDataSourceType", + "SentimentSkillLanguage", + "SnowballTokenFilterLanguage", + "SplitSkillEncoderModelName", + "SplitSkillLanguage", + "SplitSkillUnit", + "StemmerTokenFilterLanguage", + "StopwordsList", + "TextSplitMode", + "TextTranslationSkillLanguage", + "TokenCharacterKind", + "TokenFilterName", + "VectorEncodingFormat", + "VectorSearchAlgorithmKind", + "VectorSearchAlgorithmMetric", + "VectorSearchCompressionKind", + "VectorSearchCompressionRescoreStorageMethod", + "VectorSearchCompressionTarget", + "VectorSearchVectorizerKind", + "VisualFeature", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py deleted file mode 100644 index ec5b4f4937eb..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_edm.py +++ /dev/null @@ -1,19 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -String = "Edm.String" -Int32 = "Edm.Int32" -Int64 = "Edm.Int64" -Single = "Edm.Single" -Double = "Edm.Double" -Boolean = "Edm.Boolean" -DateTimeOffset = "Edm.DateTimeOffset" -GeographyPoint = "Edm.GeographyPoint" -ComplexType = "Edm.ComplexType" - - -def Collection(typ: str) -> str: - return "Collection({})".format(typ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_search_service_client_enums.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py similarity index 83% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_search_service_client_enums.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py index 04ac6e62e675..3a034616f35f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_search_service_client_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -12,29 +14,29 @@ class AIFoundryModelCatalogName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The name of the embedding model from the Azure AI Foundry Catalog that will be called.""" - OPEN_AI_CLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 = "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32" - OPEN_AI_CLIP_IMAGE_TEXT_EMBEDDINGS_VI_T_LARGE_PATCH14_336 = ( - "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336" - ) + OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 = "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32" + """OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32""" + OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VI_T_LARGE_PATCH14336 = "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336" + """OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336""" FACEBOOK_DINO_V2_IMAGE_EMBEDDINGS_VI_T_BASE = "Facebook-DinoV2-Image-Embeddings-ViT-Base" + """Facebook-DinoV2-Image-Embeddings-ViT-Base""" FACEBOOK_DINO_V2_IMAGE_EMBEDDINGS_VI_T_GIANT = "Facebook-DinoV2-Image-Embeddings-ViT-Giant" + """Facebook-DinoV2-Image-Embeddings-ViT-Giant""" COHERE_EMBED_V3_ENGLISH = "Cohere-embed-v3-english" + """Cohere-embed-v3-english""" COHERE_EMBED_V3_MULTILINGUAL = "Cohere-embed-v3-multilingual" - COHERE_EMBED_V4 = "Cohere-embed-v4" - """Cohere embed v4 model for generating embeddings from both text and images.""" + """Cohere-embed-v3-multilingual""" class AzureOpenAIModelName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The Azure Open AI model name that will be called.""" TEXT_EMBEDDING_ADA002 = "text-embedding-ada-002" + """TextEmbeddingAda002 model.""" TEXT_EMBEDDING3_LARGE = "text-embedding-3-large" + """TextEmbedding3Large model.""" TEXT_EMBEDDING3_SMALL = "text-embedding-3-small" - GPT4_O = "gpt-4o" - GPT4_O_MINI = "gpt-4o-mini" - GPT41 = "gpt-4.1" - GPT41_MINI = "gpt-4.1-mini" - GPT41_NANO = "gpt-4.1-nano" + """TextEmbedding3Small model.""" class BlobIndexerDataToExtract(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -111,7 +113,8 @@ class CharFilterName(str, Enum, metaclass=CaseInsensitiveEnumMeta): HTML_STRIP = "html_strip" """A character filter that attempts to strip out HTML constructs. See - https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.html""" + `https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.html + `_""" class ChatCompletionExtraParametersBehavior(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -126,13 +129,14 @@ class ChatCompletionExtraParametersBehavior(str, Enum, metaclass=CaseInsensitive class ChatCompletionResponseFormatType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies how the LLM should format the response. Possible values: 'text' (plain string), - 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). - """ + """Specifies how the LLM should format the response.""" TEXT = "text" + """Plain text response format.""" JSON_OBJECT = "jsonObject" + """Arbitrary JSON object response format.""" JSON_SCHEMA = "jsonSchema" + """JSON schema-adhering response format.""" class CjkBigramTokenFilterScripts(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -299,12 +303,6 @@ class EntityRecognitionSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMet """Turkish""" -class Enum0(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum0.""" - - RETURN_REPRESENTATION = "return=representation" - - class ImageAnalysisSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The language codes supported for input by ImageAnalysisSkill.""" @@ -570,6 +568,14 @@ class KnowledgeSourceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """A knowledge source that reads data from a Search Index.""" AZURE_BLOB = "azureBlob" """A knowledge source that read and ingest data from Azure Blob Storage to a Search Index.""" + INDEXED_SHARE_POINT = "indexedSharePoint" + """A knowledge source that reads data from indexed SharePoint.""" + INDEXED_ONE_LAKE = "indexedOneLake" + """A knowledge source that reads data from indexed OneLake.""" + WEB = "web" + """A knowledge source that reads data from the web.""" + REMOTE_SHARE_POINT = "remoteSharePoint" + """A knowledge source that reads data from remote SharePoint.""" class LexicalAnalyzerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -686,7 +692,7 @@ class LexicalAnalyzerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): MR_MICROSOFT = "mr.microsoft" """Microsoft analyzer for Marathi.""" NB_MICROSOFT = "nb.microsoft" - """Microsoft analyzer for Norwegian (Bokmål).""" + """Microsoft analyzer for Norwegian (BokmÃ¥l).""" NO_LUCENE = "no.lucene" """Lucene analyzer for Norwegian.""" FA_LUCENE = "fa.lucene" @@ -751,23 +757,29 @@ class LexicalAnalyzerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Standard Lucene analyzer.""" STANDARD_ASCII_FOLDING_LUCENE = "standardasciifolding.lucene" """Standard ASCII Folding Lucene analyzer. See - https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#Analyzers""" + `https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#Analyzers + `_""" KEYWORD = "keyword" """Treats the entire content of a field as a single token. This is useful for data like zip codes, ids, and some product names. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordAnalyzer.html + `_""" PATTERN = "pattern" """Flexibly separates text into terms via a regular expression pattern. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/PatternAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/PatternAnalyzer.html + `_""" SIMPLE = "simple" """Divides text at non-letters and converts them to lower case. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/SimpleAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/SimpleAnalyzer.html + `_""" STOP = "stop" """Divides text at non-letters; Applies the lowercase and stopword token filters. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopAnalyzer.html + `_""" WHITESPACE = "whitespace" """An analyzer that uses the whitespace tokenizer. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceAnalyzer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceAnalyzer.html + `_""" class LexicalNormalizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -777,19 +789,24 @@ class LexicalNormalizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such equivalents exist. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html + `_""" ELISION = "elision" """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html + `_""" LOWERCASE = "lowercase" """Normalizes token text to lowercase. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html + `_""" STANDARD = "standard" """Standard normalizer, which consists of lowercase and asciifolding. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html + `_""" UPPERCASE = "uppercase" """Normalizes token text to uppercase. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html + `_""" class LexicalTokenizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -797,42 +814,53 @@ class LexicalTokenizerName(str, Enum, metaclass=CaseInsensitiveEnumMeta): CLASSIC = "classic" """Grammar-based tokenizer that is suitable for processing most European-language documents. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicTokenizer.html + `_""" EDGE_N_GRAM = "edgeNGram" """Tokenizes the input from an edge into n-grams of the given size(s). See - https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenizer.html""" + `https://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenizer.html + `_""" KEYWORD = "keyword_v2" """Emits the entire input as a single token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/KeywordTokenizer.html + `_""" LETTER = "letter" """Divides text at non-letters. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LetterTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LetterTokenizer.html + `_""" LOWERCASE = "lowercase" """Divides text at non-letters and converts them to lower case. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LowerCaseTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LowerCaseTokenizer.html + `_""" MICROSOFT_LANGUAGE_TOKENIZER = "microsoft_language_tokenizer" """Divides text using language-specific rules.""" MICROSOFT_LANGUAGE_STEMMING_TOKENIZER = "microsoft_language_stemming_tokenizer" """Divides text using language-specific rules and reduces words to their base forms.""" N_GRAM = "nGram" """Tokenizes the input into n-grams of the given size(s). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenizer.html + `_""" PATH_HIERARCHY = "path_hierarchy_v2" """Tokenizer for path-like hierarchies. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/path/PathHierarchyTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/path/PathHierarchyTokenizer.html + `_""" PATTERN = "pattern" """Tokenizer that uses regex pattern matching to construct distinct tokens. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/pattern/PatternTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/pattern/PatternTokenizer.html + `_""" STANDARD = "standard_v2" """Standard Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop filter. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/StandardTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/StandardTokenizer.html + `_""" UAX_URL_EMAIL = "uax_url_email" """Tokenizes urls and emails as one token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/UAX29URLEmailTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/UAX29URLEmailTokenizer.html + `_""" WHITESPACE = "whitespace" """Divides text at whitespace. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceTokenizer.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/WhitespaceTokenizer.html + `_""" class MarkdownHeaderDepth(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -926,7 +954,7 @@ class MicrosoftStemmingTokenizerLanguage(str, Enum, metaclass=CaseInsensitiveEnu MARATHI = "marathi" """Selects the Microsoft stemming tokenizer for Marathi.""" NORWEGIAN_BOKMAAL = "norwegianBokmaal" - """Selects the Microsoft stemming tokenizer for Norwegian (Bokmål).""" + """Selects the Microsoft stemming tokenizer for Norwegian (BokmÃ¥l).""" POLISH = "polish" """Selects the Microsoft stemming tokenizer for Polish.""" PORTUGUESE = "portuguese" @@ -1015,7 +1043,7 @@ class MicrosoftTokenizerLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): MARATHI = "marathi" """Selects the Microsoft tokenizer for Marathi.""" NORWEGIAN_BOKMAAL = "norwegianBokmaal" - """Selects the Microsoft tokenizer for Norwegian (Bokmål).""" + """Selects the Microsoft tokenizer for Norwegian (BokmÃ¥l).""" POLISH = "polish" """Selects the Microsoft tokenizer for Polish.""" PORTUGUESE = "portuguese" @@ -1060,11 +1088,14 @@ class OcrLineEnding(str, Enum, metaclass=CaseInsensitiveEnumMeta): SPACE = "space" """Lines are separated by a single space character.""" CARRIAGE_RETURN = "carriageReturn" - """Lines are separated by a carriage return ('\\r') character.""" + """Lines are separated by a carriage return (' +') character.""" LINE_FEED = "lineFeed" - """Lines are separated by a single line feed ('\\n') character.""" + """Lines are separated by a single line feed (' +') character.""" CARRIAGE_RETURN_LINE_FEED = "carriageReturnLineFeed" - """Lines are separated by a carriage return and a line feed ('\\r\\n') character.""" + """Lines are separated by a carriage return and a line feed (' +') character.""" class OcrSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1395,7 +1426,7 @@ class OcrSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): UZ = "uz" """Uzbek (Latin)""" VO = "vo" - """Volapük""" + """Volapük""" WAE = "wae" """Walser""" CY = "cy" @@ -1410,8 +1441,6 @@ class OcrSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Zulu""" UNK = "unk" """Unknown (All)""" - IS_ENUM = "is" - """Icelandic""" class PermissionFilter(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1445,9 +1474,9 @@ class PhoneticEncoder(str, Enum, metaclass=CaseInsensitiveEnumMeta): NYSIIS = "nysiis" """Encodes a token into a NYSIIS value.""" KOELNER_PHONETIK = "koelnerPhonetik" - """Encodes a token using the Kölner Phonetik algorithm.""" + """Encodes a token using the Kölner Phonetik algorithm.""" HAASE_PHONETIK = "haasePhonetik" - """Encodes a token using the Haase refinement of the Kölner Phonetik algorithm.""" + """Encodes a token using the Haase refinement of the Kölner Phonetik algorithm.""" BEIDER_MORSE = "beiderMorse" """Encodes a token into a Beider-Morse value.""" @@ -1470,7 +1499,7 @@ class RankingOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): BOOSTED_RERANKER_SCORE = "BoostedRerankerScore" """Sets sort order as BoostedRerankerScore""" - RE_RANKER_SCORE = "RerankerScore" + RERANKER_SCORE = "RerankerScore" """Sets sort order as ReRankerScore""" @@ -1592,7 +1621,9 @@ class SearchIndexPermissionFilterOption(str, Enum, metaclass=CaseInsensitiveEnum """A value indicating whether permission filtering is enabled for the index.""" ENABLED = "enabled" + """enabled.""" DISABLED = "disabled" + """disabled.""" class SentimentSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1766,8 +1797,6 @@ class SplitSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Urdu""" ZH = "zh" """Chinese (Simplified)""" - IS_ENUM = "is" - """Icelandic""" class SplitSkillUnit(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1858,11 +1887,11 @@ class StemmerTokenFilterLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): LATVIAN = "latvian" """Selects the Lucene stemming tokenizer for Latvian.""" NORWEGIAN = "norwegian" - """Selects the Lucene stemming tokenizer for Norwegian (Bokmål).""" + """Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l).""" LIGHT_NORWEGIAN = "lightNorwegian" - """Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does light stemming.""" + """Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l) that does light stemming.""" MINIMAL_NORWEGIAN = "minimalNorwegian" - """Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does minimal stemming.""" + """Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l) that does minimal stemming.""" LIGHT_NYNORSK = "lightNynorsk" """Selects the Lucene stemming tokenizer for Norwegian (Nynorsk) that does light stemming.""" MINIMAL_NYNORSK = "minimalNynorsk" @@ -2116,8 +2145,6 @@ class TextTranslationSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta) """Malayalam""" PA = "pa" """Punjabi""" - IS_ENUM = "is" - """Icelandic""" class TokenCharacterKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -2140,109 +2167,141 @@ class TokenFilterName(str, Enum, metaclass=CaseInsensitiveEnumMeta): ARABIC_NORMALIZATION = "arabic_normalization" """A token filter that applies the Arabic normalizer to normalize the orthography. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html + `_""" APOSTROPHE = "apostrophe" """Strips all characters after an apostrophe (including the apostrophe itself). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/tr/ApostropheFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/tr/ApostropheFilter.html + `_""" ASCII_FOLDING = "asciifolding" """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such equivalents exist. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html + `_""" CJK_BIGRAM = "cjk_bigram" """Forms bigrams of CJK terms that are generated from the standard tokenizer. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html + `_""" CJK_WIDTH = "cjk_width" - """Normalizes CJK width differences. Folds fullwidth ASCII variants into the equivalent basic + """Normalizes CJK width differences. Folds full-width ASCII variants into the equivalent basic Latin, and half-width Katakana variants into the equivalent Kana. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html + `_""" CLASSIC = "classic" """Removes English possessives, and dots from acronyms. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/standard/ClassicFilter.html + `_""" COMMON_GRAM = "common_grams" """Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed too, with bigrams overlaid. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html + `_""" EDGE_N_GRAM = "edgeNGram_v2" """Generates n-grams of the given size(s) starting from the front or the back of an input token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html + `_""" ELISION = "elision" """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html + `_""" GERMAN_NORMALIZATION = "german_normalization" """Normalizes German characters according to the heuristics of the German2 snowball algorithm. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html + `_""" HINDI_NORMALIZATION = "hindi_normalization" """Normalizes text in Hindi to remove some differences in spelling variations. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html + `_""" INDIC_NORMALIZATION = "indic_normalization" """Normalizes the Unicode representation of text in Indian languages. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html + `_""" KEYWORD_REPEAT = "keyword_repeat" """Emits each incoming token twice, once as keyword and once as non-keyword. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html + `_""" K_STEM = "kstem" """A high-performance kstem filter for English. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html + `_""" LENGTH = "length" """Removes words that are too long or too short. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html + `_""" LIMIT = "limit" """Limits the number of tokens while indexing. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html + `_""" LOWERCASE = "lowercase" """Normalizes token text to lower case. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html + `_""" N_GRAM = "nGram_v2" """Generates n-grams of the given size(s). See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html + `_""" PERSIAN_NORMALIZATION = "persian_normalization" """Applies normalization for Persian. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html + `_""" PHONETIC = "phonetic" """Create tokens for phonetic matches. See - https://lucene.apache.org/core/4_10_3/analyzers-phonetic/org/apache/lucene/analysis/phonetic/package-tree.html""" + `https://lucene.apache.org/core/4_10_3/analyzers-phonetic/org/apache/lucene/analysis/phonetic/package-tree.html + `_""" PORTER_STEM = "porter_stem" """Uses the Porter stemming algorithm to transform the token stream. See - http://tartarus.org/~martin/PorterStemmer""" + `http://tartarus.org/~martin/PorterStemmer `_""" REVERSE = "reverse" """Reverses the token string. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html + `_""" SCANDINAVIAN_NORMALIZATION = "scandinavian_normalization" """Normalizes use of the interchangeable Scandinavian characters. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html + `_""" SCANDINAVIAN_FOLDING_NORMALIZATION = "scandinavian_folding" - """Folds Scandinavian characters åÅäæÄÆ->a and öÖøØ->o. It also discriminates against use of - double vowels aa, ae, ao, oe and oo, leaving just the first one. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html""" + """Folds Scandinavian characters åÅäæÄÆ->a and öÖøØ->o. It also discriminates + against use of double vowels aa, ae, ao, oe and oo, leaving just the first one. See + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html + `_""" SHINGLE = "shingle" """Creates combinations of tokens as a single token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/shingle/ShingleFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/shingle/ShingleFilter.html + `_""" SNOWBALL = "snowball" """A filter that stems words using a Snowball-generated stemmer. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/snowball/SnowballFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/snowball/SnowballFilter.html + `_""" SORANI_NORMALIZATION = "sorani_normalization" """Normalizes the Unicode representation of Sorani text. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html + `_""" STEMMER = "stemmer" """Language specific stemming filter. See - https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters""" + `https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters + `_""" STOPWORDS = "stopwords" """Removes stop words from a token stream. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html + `_""" TRIM = "trim" """Trims leading and trailing whitespace from tokens. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html + `_""" TRUNCATE = "truncate" """Truncates the terms to a specific length. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html + `_""" UNIQUE = "unique" """Filters out tokens with same text as the previous token. See - http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html""" + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html + `_""" UPPERCASE = "uppercase" """Normalizes token text to upper case. See - https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html""" + `https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html + `_""" WORD_DELIMITER = "word_delimiter" """Splits words into subwords and performs optional transformations on subword groups.""" @@ -2314,6 +2373,7 @@ class VectorSearchCompressionTarget(str, Enum, metaclass=CaseInsensitiveEnumMeta """The quantized data type of compressed vector values.""" INT8 = "int8" + """8-bit signed integer.""" class VectorSearchVectorizerKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py deleted file mode 100644 index 3ed8dfa370f6..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_index.py +++ /dev/null @@ -1,908 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from typing import Any, Dict, Union, List, Optional, MutableMapping, Callable, cast -from typing_extensions import Self -from .._generated._utils import serialization as _serialization -from ._edm import Collection, ComplexType, String -from .._generated.models import ( - SearchField as _SearchField, - SearchIndex as _SearchIndex, - PatternTokenizer as _PatternTokenizer, - LexicalAnalyzerName, - VectorEncodingFormat, - SearchFieldDataType, - ScoringProfile, - CorsOptions, - SearchSuggester, - LexicalAnalyzer, - LexicalTokenizer, - TokenFilter, - CharFilter, - LexicalNormalizer, - SimilarityAlgorithm, - SemanticSearch, - VectorSearch, - SearchIndexPermissionFilterOption, - PermissionFilter, -) -from ._models import ( - pack_analyzer, - unpack_analyzer, - PatternTokenizer, - SearchResourceEncryptionKey, -) - - -__all__ = ("ComplexField", "SearchableField", "SimpleField") - - -class SearchField(_serialization.Model): - # pylint: disable=too-many-instance-attributes - """Represents a field in an index definition, which describes the name, data type, and search behavior of a field. - - All required parameters must be populated in order to send to Azure. - - :ivar name: The name of the field, which must be unique within the fields collection of the - index or parent field. Required. - :vartype name: str - :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", - "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", - "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". - :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType - :ivar key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type Edm.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is false for simple fields and null for complex fields. - :vartype key: bool - :ivar stored: An immutable value indicating whether the field will be persisted separately on - disk to be returned in a search result. You can disable this option if you don't plan to return - the field contents in a search response to save on storage overhead. This can only be set - during index creation and only for vector fields. This property cannot be changed for existing - fields or set as false for new fields. If this property is set as false, the property - 'hidden' must be set to true. This property must be true or unset for key fields, - for new fields, and for non-vector fields, and it must be null for complex fields. Disabling - this property will reduce index storage requirements. The default is true for vector fields. - :vartype stored: bool - :ivar searchable: A value indicating whether the field is full-text searchable. This means it - will undergo analysis such as word-breaking during indexing. If you set a searchable field to a - value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Fields of type Edm.String or - Collection(Edm.String) are searchable by default. This property must be false for simple fields - of other non-string data types, and it must be null for complex fields. Note: searchable fields - consume extra space in your index since Azure Cognitive Search will store an additional - tokenized version of the field value for full-text searches. If you want to save space in your - index and you don't need a field to be included in searches, set searchable to false. - :vartype searchable: bool - :ivar filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so - comparisons are for exact matches only. For example, if you set such a field f to "sunny day", - $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property - must be null for complex fields. Default is true for simple fields and null for complex fields. - :vartype filterable: bool - :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default Azure Cognitive Search sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. Complex fields - cannot be sortable and the sortable property must be null for such fields. The default for - sortable is true for single-valued simple fields, false for multi-valued simple fields, and - null for complex fields. - :vartype sortable: bool - :ivar facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or - Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple - fields. - :vartype facetable: bool - :ivar permission_filter: A value indicating whether the field should be used as a permission - filter. Known values are: "userIds", "groupIds", and "rbacScope". - :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :ivar analyzer_name: The name of the analyzer to use for the field. This option can be used only - with searchable fields and it can't be set together with either searchAnalyzer or - indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null - for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar search_analyzer_name: The name of the analyzer used at search time for the field. This option - can be used only with searchable fields. It must be set together with indexAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. This - analyzer can be updated on an existing field. Must be null for complex fields. Known values - are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", - "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", - "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", - "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", - "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", - "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", - "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", - "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", - "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", - "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", - "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar index_analyzer_name: The name of the analyzer used at indexing time for the field. This option - can be used only with searchable fields. It must be set together with searchAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. Once the - analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known - values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", - "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar normalizer_name: The name of the normalizer to use for the field. This option can be used only - with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it - cannot be changed for the field. Must be null for complex fields. Known values are: - "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName - :ivar vector_search_dimensions: The dimensionality of the vector field. - :vartype vector_search_dimensions: int - :ivar vector_search_profile_name: The name of the vector search profile that specifies the algorithm - to use when searching the vector field. - :vartype vector_search_profile_name: str - :ivar synonym_map_names: A list of the names of synonym maps to associate with this field. This - option can be used only with searchable fields. Currently only one synonym map per field is - supported. Assigning a synonym map to a field ensures that query terms targeting that field are - expanded at query-time using the rules in the synonym map. This attribute can be changed on - existing fields. Must be null or an empty collection for complex fields. - :vartype synonym_map_names: list[str] - :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or - Collection(Edm.ComplexType). Must be null or empty for simple fields. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" - :vartype vector_encoding_format: str or ~azure.search.documents.indexes.models.VectorEncodingFormat - """ - - def __init__( - self, - *, - name: str, - type: Union[str, SearchFieldDataType], - key: Optional[bool] = None, - hidden: Optional[bool] = None, - stored: Optional[bool] = None, - searchable: Optional[bool] = None, - filterable: Optional[bool] = None, - sortable: Optional[bool] = None, - facetable: Optional[bool] = None, - permission_filter: Optional[Union[str, PermissionFilter]] = None, - analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - synonym_map_names: Optional[List[str]] = None, - fields: Optional[List["SearchField"]] = None, - normalizer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - vector_search_dimensions: Optional[int] = None, - vector_search_profile_name: Optional[str] = None, - vector_encoding_format: Optional[Union[str, VectorEncodingFormat]] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.type = type - self.key = key - self.hidden = hidden - self.stored = stored - self.searchable = searchable - self.filterable = filterable - self.sortable = sortable - self.facetable = facetable - self.permission_filter = permission_filter - self.analyzer_name = analyzer_name - self.search_analyzer_name = search_analyzer_name - self.index_analyzer_name = index_analyzer_name - self.synonym_map_names = synonym_map_names - self.fields = fields - self.normalizer_name = normalizer_name - self.vector_search_dimensions = vector_search_dimensions - self.vector_search_profile_name = vector_search_profile_name - self.vector_encoding_format = vector_encoding_format - - def _to_generated(self) -> _SearchField: - fields = [pack_search_field(x) for x in self.fields] if self.fields else None - retrievable = not self.hidden if self.hidden is not None else None - return _SearchField( - name=self.name, - type=self.type, - key=self.key, - retrievable=retrievable, - stored=self.stored, - searchable=self.searchable, - filterable=self.filterable, - sortable=self.sortable, - facetable=self.facetable, - permission_filter=self.permission_filter, - analyzer=self.analyzer_name, - search_analyzer=self.search_analyzer_name, - index_analyzer=self.index_analyzer_name, - normalizer=self.normalizer_name, - synonym_maps=self.synonym_map_names, - fields=fields, - vector_search_dimensions=self.vector_search_dimensions, - vector_search_profile_name=self.vector_search_profile_name, - vector_encoding_format=self.vector_encoding_format, - ) - - @classmethod - def _from_generated(cls, search_field) -> Optional[Self]: - if not search_field: - return None - # pylint:disable=protected-access - fields = ( - [cast(SearchField, SearchField._from_generated(x)) for x in search_field.fields] - if search_field.fields - else None - ) - hidden = not search_field.retrievable if search_field.retrievable is not None else None - try: - normalizer = search_field.normalizer - except AttributeError: - normalizer = None - return cls( - name=search_field.name, - type=search_field.type, - key=search_field.key, - hidden=hidden, - stored=search_field.stored, - searchable=search_field.searchable, - filterable=search_field.filterable, - sortable=search_field.sortable, - facetable=search_field.facetable, - permission_filter=search_field.permission_filter, - analyzer_name=search_field.analyzer, - search_analyzer_name=search_field.search_analyzer, - index_analyzer_name=search_field.index_analyzer, - normalizer_name=normalizer, - synonym_map_names=search_field.synonym_maps, - fields=fields, - vector_search_dimensions=search_field.vector_search_dimensions, - vector_search_profile_name=search_field.vector_search_profile_name, - vector_encoding_format=search_field.vector_encoding_format, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchField instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchField instance - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchField.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchField instance - :rtype: SearchField - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchField.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -def SimpleField( - *, - name: str, - type: str, - key: bool = False, - hidden: bool = False, - filterable: bool = False, - sortable: bool = False, - facetable: bool = False, - **kw # pylint:disable=unused-argument -) -> SearchField: - """Configure a simple field for an Azure Search Index - - :keyword name: Required. The name of the field, which must be unique within the fields collection - of the index or parent field. - :paramtype name: str - :keyword type: Required. The data type of the field. Possible values include: SearchFieldDataType.String, - SearchFieldDataType.Int32, SearchFieldDataType.Int64, SearchFieldDataType.Double, SearchFieldDataType.Boolean, - SearchFieldDataType.DateTimeOffset, SearchFieldDataType.GeographyPoint, SearchFieldDataType.ComplexType, - from `azure.search.documents.SearchFieldDataType`. - :paramtype type: str - :keyword key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type SearchFieldDataType.String. Key fields can be used to look up documents directly and - update or delete specific documents. Default is False - :paramtype key: bool - :keyword hidden: A value indicating whether the field can be returned in a search result. - You can enable this option if you want to use a field (for example, margin) as a filter, - sorting, or scoring mechanism but do not want the field to be visible to the end user. This - property must be False for key fields. This property can be changed on existing fields. - Enabling this property does not cause any increase in index storage requirements. Default is - False. - :paramtype hidden: bool - :keyword filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields of type - SearchFieldDataType.String or Collection(SearchFieldDataType.String) that are filterable do - not undergo word-breaking, so comparisons are for exact matches only. For example, if you - set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but - $filter=f eq 'sunny day' will. This property must be null for complex fields. Default is False - :paramtype filterable: bool - :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default Azure Cognitive Search sorts results by score, but in many experiences - users will want to sort by fields in the documents. A simple field can be sortable only if it - is single-valued (it has a single value in the scope of the parent document). Simple collection - fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex - collections are also multi-valued, and therefore cannot be sortable. This is true whether it's - an immediate parent field, or an ancestor field, that's the complex collection. The default is - False. - :paramtype sortable: bool - :keyword facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). Fields of type SearchFieldDataType.GeographyPoint or - Collection(SearchFieldDataType.GeographyPoint) cannot be facetable. Default is False. - :paramtype facetable: bool - :return: The search field object. - :rtype: SearchField - """ - result: Dict[str, Any] = { - "name": name, - "type": type, - "key": key, - "searchable": False, - "filterable": filterable, - "facetable": facetable, - "sortable": sortable, - "hidden": hidden, - } - return SearchField(**result) - - -def SearchableField( - *, - name: str, - collection: bool = False, - key: bool = False, - hidden: bool = False, - searchable: bool = True, - filterable: bool = False, - sortable: bool = False, - facetable: bool = False, - analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, - synonym_map_names: Optional[List[str]] = None, - **kw # pylint:disable=unused-argument -) -> SearchField: - """Configure a searchable text field for an Azure Search Index - - :keyword name: Required. The name of the field, which must be unique within the fields collection - of the index or parent field. - :paramtype name: str - :keyword collection: Whether this search field is a collection (default False) - :paramtype collection: bool - :keyword key: A value indicating whether the field uniquely identifies documents in the index. - Exactly one top-level field in each index must be chosen as the key field and it must be of - type SearchFieldDataType.String. Key fields can be used to look up documents directly and update or delete - specific documents. Default is False - :paramtype key: bool - :keyword hidden: A value indicating whether the field can be returned in a search result. - You can enable this option if you want to use a field (for example, margin) as a filter, - sorting, or scoring mechanism but do not want the field to be visible to the end user. This - property must be False for key fields. This property can be changed on existing fields. - Enabling this property does not cause any increase in index storage requirements. Default is - False. - :paramtype hidden: bool - :keyword searchable: A value indicating whether the field is full-text searchable. This means it - will undergo analysis such as word-breaking during indexing. If you set a searchable field to a - value like "sunny day", internally it will be split into the individual tokens "sunny" and - "day". This enables full-text searches for these terms. Note: searchable fields - consume extra space in your index since Azure Cognitive Search will store an additional - tokenized version of the field value for full-text searches. If you want to save space in your - index and you don't need a field to be included in searches, set searchable to false. Default - is True. - :paramtype searchable: bool - :keyword filterable: A value indicating whether to enable the field to be referenced in $filter - queries. filterable differs from searchable in how strings are handled. Fields that are - filterable do not undergo word-breaking, so comparisons are for exact matches only. For example, - if you set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but - $filter=f eq 'sunny day' will. Default is False. - :paramtype filterable: bool - :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby - expressions. By default Azure Cognitive Search sorts results by score, but in many experiences - users will want to sort by fields in the documents. The default is False. - :paramtype sortable: bool - :keyword facetable: A value indicating whether to enable the field to be referenced in facet - queries. Typically used in a presentation of search results that includes hit count by category - (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so - on). Default is False. - :paramtype facetable: bool - :keyword analyzer_name: The name of the analyzer to use for the field. This option can't be set together - with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed - for the field. Possible values include: 'ar.microsoft', 'ar.lucene', 'hy.lucene', - 'bn.microsoft', 'eu.lucene', 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh- - Hans.microsoft', 'zh-Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', - 'cs.microsoft', 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', - 'en.microsoft', 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', - 'fr.lucene', 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', - 'gu.microsoft', 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', - 'is.microsoft', 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', - 'ja.microsoft', 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', - 'lv.lucene', 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', - 'no.lucene', 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt- - PT.microsoft', 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', - 'ru.lucene', 'sr-cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', - 'es.microsoft', 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', - 'th.microsoft', 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', - 'vi.microsoft', 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', - 'simple', 'stop', 'whitespace'. - :paramtype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword search_analyzer_name: The name of the analyzer used at search time for the field. It must be - set together with indexAnalyzer and it cannot be set together with the analyzer option. This - property cannot be set to the name of a language analyzer; use the analyzer property instead - if you need a language analyzer. This analyzer can be updated on an existing field. Possible - values include: - 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', 'bg.microsoft', - 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh-Hans.lucene', 'zh- - Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', 'cs.lucene', 'da.microsoft', - 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', 'en.lucene', 'et.microsoft', - 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', 'gl.lucene', 'de.microsoft', - 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', 'he.microsoft', 'hi.microsoft', - 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', 'id.microsoft', 'id.lucene', - 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', 'ja.lucene', 'kn.microsoft', - 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', 'lt.microsoft', 'ml.microsoft', - 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', 'fa.lucene', 'pl.microsoft', - 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', 'pt-PT.lucene', - 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- - cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', - 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', - 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', - 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', - 'whitespace'. - :paramtype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword index_analyzer_name: The name of the analyzer used at indexing time for the field. - It must be set together with searchAnalyzer and it cannot be set together with the analyzer - option. This property cannot be set to the name of a language analyzer; use the analyzer - property instead if you need a language analyzer. Once the analyzer is chosen, it cannot be - changed for the field. Possible values include: - 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', - 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh- - Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', - 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', - 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', - 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', - 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', - 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', - 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', - 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', - 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', - 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- - cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', - 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', - 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', - 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', - 'whitespace'. - :paramtype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword synonym_map_names: A list of the names of synonym maps to associate with this field. Currently - only one synonym map per field is supported. Assigning a synonym map to a field ensures that - query terms targeting that field are expanded at query-time using the rules in the synonym map. - This attribute can be changed on existing fields. - :paramtype synonym_map_names: list[str] - :return: The search field object. - :rtype: SearchField - """ - typ = Collection(String) if collection else String - result: Dict[str, Any] = { - "name": name, - "type": typ, - "key": key, - "searchable": searchable, - "filterable": filterable, - "facetable": facetable, - "sortable": sortable, - "hidden": hidden, - } - if analyzer_name: - result["analyzer_name"] = analyzer_name - if search_analyzer_name: - result["search_analyzer_name"] = search_analyzer_name - if index_analyzer_name: - result["index_analyzer_name"] = index_analyzer_name - if synonym_map_names: - result["synonym_map_names"] = synonym_map_names - return SearchField(**result) - - -def ComplexField( - *, - name: str, - collection: bool = False, - fields: Optional[List[SearchField]] = None, - **kw # pylint:disable=unused-argument -) -> SearchField: - """Configure a Complex or Complex collection field for an Azure Search Index - - :keyword name: Required. The name of the field, which must be unique within the fields collection - of the index or parent field. - :paramtype name: str - :keyword collection: Whether this complex field is a collection (default False) - :paramtype collection: bool - :keyword fields: A list of sub-fields - :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] - :return: The search field object. - :rtype: SearchField - """ - typ = Collection(ComplexType) if collection else ComplexType - result: Dict[str, Any] = {"name": name, "type": typ, "fields": fields} - return SearchField(**result) - - -class SearchIndex(_serialization.Model): - # pylint: disable=too-many-instance-attributes - """Represents a search index definition, which describes the fields and search behavior of an index. - - All required parameters must be populated in order to send to Azure. - - :ivar name: Required. The name of the index. - :vartype name: str - :ivar description: The description of the index. - :vartype description: str - :ivar fields: Required. The fields of the index. - :vartype fields: list[~azure.search.documents.indexes.models.SearchField] - :ivar scoring_profiles: The scoring profiles for the index. - :vartype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] - :ivar default_scoring_profile: The name of the scoring profile to use if none is specified in - the query. If this property is not set and no scoring profile is specified in the query, then - default scoring (tf-idf) will be used. - :vartype default_scoring_profile: str - :ivar cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. - :vartype cors_options: ~azure.search.documents.indexes.models.CorsOptions - :ivar suggesters: The suggesters for the index. - :vartype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] - :ivar analyzers: The analyzers for the index. - :vartype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] - :ivar tokenizers: The tokenizers for the index. - :vartype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] - :ivar token_filters: The token filters for the index. - :vartype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] - :ivar char_filters: The character filters for the index. - :vartype char_filters: list[~azure.search.documents.indexes.models.CharFilter] - :ivar normalizers: The normalizers for the index. - :vartype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data in Azure Cognitive - Search. Once you have encrypted your data, it will always remain encrypted. Azure Cognitive - Search will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your data will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar similarity: The type of similarity algorithm to be used when scoring and ranking the - documents matching a search query. The similarity algorithm can only be defined at index - creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity - algorithm is used. - :vartype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm - :ivar semantic_search: Defines parameters for a search index that influence semantic capabilities. - :vartype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch - :ivar vector_search: Defines parameters for a search index that influence scoring in a vector space. - :vartype vector_search: ~azure.search.documents.indexes.models.VectorSearch - :ivar permission_filter_option: A value indicating whether permission filtering is enabled for - the index. Known values are: "enabled" and "disabled". - :vartype permission_filter_option: str or - ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption - :ivar e_tag: The ETag of the index. - :vartype e_tag: str - """ - - def __init__( - self, - *, - name: str, - fields: List[SearchField], - description: Optional[str] = None, - scoring_profiles: Optional[List[ScoringProfile]] = None, - default_scoring_profile: Optional[str] = None, - cors_options: Optional[CorsOptions] = None, - suggesters: Optional[List[SearchSuggester]] = None, - analyzers: Optional[List[LexicalAnalyzer]] = None, - tokenizers: Optional[List[LexicalTokenizer]] = None, - token_filters: Optional[List[TokenFilter]] = None, - char_filters: Optional[List[CharFilter]] = None, - normalizers: Optional[List[LexicalNormalizer]] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - similarity: Optional[SimilarityAlgorithm] = None, - semantic_search: Optional[SemanticSearch] = None, - vector_search: Optional[VectorSearch] = None, - permission_filter_option: Optional[Union[str, SearchIndexPermissionFilterOption]] = None, - e_tag: Optional[str] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.fields = fields - self.description = description - self.scoring_profiles = scoring_profiles - self.default_scoring_profile = default_scoring_profile - self.cors_options = cors_options - self.suggesters = suggesters - self.analyzers = analyzers - self.tokenizers = tokenizers - self.token_filters = token_filters - self.char_filters = char_filters - self.normalizers = normalizers - self.encryption_key = encryption_key - self.similarity = similarity - self.semantic_search = semantic_search - self.vector_search = vector_search - self.permission_filter_option = permission_filter_option - self.e_tag = e_tag - - def _to_generated(self) -> _SearchIndex: - if self.analyzers: - analyzers = [pack_analyzer(x) for x in self.analyzers] # type: ignore # mypy: ignore - else: - analyzers = None - if self.tokenizers: - tokenizers = [ - x._to_generated() if isinstance(x, PatternTokenizer) else x # pylint:disable=protected-access - for x in self.tokenizers - ] - else: - tokenizers = None - if self.fields: - fields = [pack_search_field(x) for x in self.fields] - else: - fields = [] - return _SearchIndex( - name=self.name, - description=self.description, - fields=fields, - scoring_profiles=self.scoring_profiles, - default_scoring_profile=self.default_scoring_profile, - cors_options=self.cors_options, - suggesters=self.suggesters, - analyzers=analyzers, - tokenizers=tokenizers, - token_filters=self.token_filters, - char_filters=self.char_filters, - normalizers=self.normalizers, - # pylint:disable=protected-access - encryption_key=self.encryption_key._to_generated() if self.encryption_key else None, - similarity=self.similarity, - semantic_search=self.semantic_search, - e_tag=self.e_tag, - vector_search=self.vector_search, - permission_filter_option=self.permission_filter_option, - ) - - @classmethod - def _from_generated(cls, search_index) -> Optional[Self]: - if not search_index: - return None - if search_index.analyzers: - analyzers = [unpack_analyzer(x) for x in search_index.analyzers] # type: ignore - else: - analyzers = None - if search_index.tokenizers: - tokenizers = [ - ( - PatternTokenizer._from_generated(x) # pylint:disable=protected-access - if isinstance(x, _PatternTokenizer) - else x - ) - for x in search_index.tokenizers - ] - else: - tokenizers = None - if search_index.fields: - # pylint:disable=protected-access - fields = [cast(SearchField, SearchField._from_generated(x)) for x in search_index.fields] - else: - fields = [] - try: - normalizers = search_index.normalizers - except AttributeError: - normalizers = None - return cls( - name=search_index.name, - description=search_index.description, - fields=fields, - scoring_profiles=search_index.scoring_profiles, - default_scoring_profile=search_index.default_scoring_profile, - cors_options=search_index.cors_options, - suggesters=search_index.suggesters, - analyzers=analyzers, - tokenizers=tokenizers, - token_filters=search_index.token_filters, - char_filters=search_index.char_filters, - normalizers=normalizers, - # pylint:disable=protected-access - encryption_key=SearchResourceEncryptionKey._from_generated(search_index.encryption_key), - similarity=search_index.similarity, - semantic_search=search_index.semantic_search, - e_tag=search_index.e_tag, - vector_search=search_index.vector_search, - permission_filter_option=search_index.permission_filter_option, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndex instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndex instance - :rtype: SearchIndex - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndex.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndex instance - :rtype: SearchIndex - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchIndex.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -def pack_search_field(search_field: SearchField) -> _SearchField: - if isinstance(search_field, dict): - name = search_field.get("name") - assert name is not None # Hint for mypy - field_type = search_field.get("type") - assert field_type is not None # Hint for mypy - key = search_field.get("key") - hidden = search_field.get("hidden") - retrievable = not hidden if hidden is not None else None - searchable = search_field.get("searchable") - filterable = search_field.get("filterable") - sortable = search_field.get("sortable") - facetable = search_field.get("facetable") - analyzer_name = search_field.get("analyzer_name") - search_analyzer_name = search_field.get("search_analyzer_name") - index_analyzer_name = search_field.get("index_analyzer_name") - normalizer = search_field.get("normalizer") - synonym_map_names = search_field.get("synonym_map_names") - fields = search_field.get("fields") - fields = [pack_search_field(x) for x in fields] if fields else None - vector_search_dimensions = search_field.get("vector_search_dimensions") - vector_search_profile_name = search_field.get("vector_search_profile_name") - return _SearchField( - name=name, - type=field_type, - key=key, - retrievable=retrievable, - searchable=searchable, - filterable=filterable, - sortable=sortable, - facetable=facetable, - analyzer=analyzer_name, - search_analyzer=search_analyzer_name, - index_analyzer=index_analyzer_name, - normalizer=normalizer, - synonym_maps=synonym_map_names, - fields=fields, - vector_search_dimensions=vector_search_dimensions, - vector_search_profile_name=vector_search_profile_name, - ) - return search_field._to_generated() # pylint:disable=protected-access diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 7a04efd01c69..4cef621fc010 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -1,227 +1,11315 @@ -# pylint: disable=too-many-lines -# ------------------------------------------------------------------------- +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- - -from typing import Any, List, Optional, MutableMapping, Dict, Callable, Union -from enum import Enum -from typing_extensions import Self -from azure.core import CaseInsensitiveEnumMeta -from .._generated._utils import serialization as _serialization -from .._generated.models import ( - LexicalAnalyzer, - LexicalTokenizer, - AnalyzeRequest, - CustomAnalyzer as _CustomAnalyzer, - EntityRecognitionSkillV3 as _EntityRecognitionSkillV3, - PatternAnalyzer as _PatternAnalyzer, - PatternTokenizer as _PatternTokenizer, - SearchResourceEncryptionKey as _SearchResourceEncryptionKey, - SearchIndexerDataSource as _SearchIndexerDataSource, - SearchIndexerSkill, - SearchIndexerSkillset as _SearchIndexerSkillset, - SentimentSkillV3 as _SentimentSkillV3, - SynonymMap as _SynonymMap, - DataSourceCredentials, - AzureActiveDirectoryApplicationCredentials, - CognitiveServicesAccount, - SearchIndexerKnowledgeStore, - SearchIndexerIndexProjection, - SearchIndexerDataContainer, - DataChangeDetectionPolicy, - DataDeletionDetectionPolicy, - SearchIndexerDataIdentity, - SearchIndexer as _SearchIndexer, - IndexingSchedule, - IndexingParameters, - FieldMapping, - SearchIndexerCache, - IndexerPermissionOption, +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from ..._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import ( + KnowledgeAgentModelKind, + KnowledgeSourceKind, + VectorSearchAlgorithmKind, + VectorSearchCompressionKind, + VectorSearchVectorizerKind, ) -DELIMITER = "|" +if TYPE_CHECKING: + from .. import models as _models + + +class CognitiveServicesAccount(_Model): + """Base type for describing any Azure AI service resource attached to a skillset. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AIServicesAccountIdentity, AIServicesAccountKey, CognitiveServicesAccountKey, + DefaultCognitiveServicesAccount + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description of the Azure AI service resource attached to a skillset.""" + + @overload + def __init__( + self, + *, + odata_type: str, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AIServicesAccountIdentity(CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.AIServicesByIdentity"): + """The multi-region account of an Azure AI service resource that's attached to a skillset. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar identity: The user-assigned managed identity used for connections to AI Service. If not + specified, the system-assigned managed identity is used. On updates to the skillset, if the + identity is unspecified, the value remains unchanged. If set to "none", the value of this + property is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. + :vartype subdomain_url: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.AIServicesByIdentity". + :vartype odata_type: str + """ + + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for connections to AI Service. If not specified, the + system-assigned managed identity is used. On updates to the skillset, if the identity is + unspecified, the value remains unchanged. If set to \"none\", the value of this property is + cleared.""" + subdomain_url: str = rest_field(name="subdomainUrl", visibility=["read", "create", "update", "delete", "query"]) + """The subdomain url for the corresponding AI Service. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.AIServicesByIdentity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.AIServicesByIdentity\".""" + + @overload + def __init__( + self, + *, + subdomain_url: str, + description: Optional[str] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.AIServicesByIdentity" # type: ignore + + +class AIServicesAccountKey(CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.AIServicesByKey"): + """The account key of an Azure AI service resource that's attached to a skillset, to be used with + the resource's subdomain. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar key: The key used to provision the Azure AI service resource attached to a skillset. + Required. + :vartype key: str + :ivar subdomain_url: The subdomain url for the corresponding AI Service. Required. + :vartype subdomain_url: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.AIServicesByKey". + :vartype odata_type: str + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key used to provision the Azure AI service resource attached to a skillset. Required.""" + subdomain_url: str = rest_field(name="subdomainUrl", visibility=["read", "create", "update", "delete", "query"]) + """The subdomain url for the corresponding AI Service. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.AIServicesByKey"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.AIServicesByKey\".""" + + @overload + def __init__( + self, + *, + key: str, + subdomain_url: str, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.AIServicesByKey" # type: ignore + + +class AIServicesVisionParameters(_Model): + """Specifies the AI Services Vision parameters for vectorizing a query image or text. + + :ivar model_version: The version of the model to use when calling the AI Services Vision + service. It will default to the latest available when not specified. Required. + :vartype model_version: str + :ivar resource_uri: The resource URI of the AI Services resource. Required. + :vartype resource_uri: str + :ivar api_key: API key of the designated AI Services resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the index, if the identity is unspecified, the value remains unchanged. If + set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + """ + + model_version: str = rest_field(name="modelVersion", visibility=["read", "create", "update", "delete", "query"]) + """The version of the model to use when calling the AI Services Vision service. It will default to + the latest available when not specified. Required.""" + resource_uri: str = rest_field(name="resourceUri", visibility=["read", "create", "update", "delete", "query"]) + """The resource URI of the AI Services resource. Required.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated AI Services resource.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the index, if the identity is unspecified, the value remains unchanged. If set to \"none\", the + value of this property is cleared.""" + + @overload + def __init__( + self, + *, + model_version: str, + resource_uri: str, + api_key: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorSearchVectorizer(_Model): + """Specifies the vectorization method to be used during query time. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AIServicesVisionVectorizer, AzureMachineLearningVectorizer, AzureOpenAIVectorizer, + WebApiVectorizer + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar kind: Type of VectorSearchVectorizer. Required. Known values are: "azureOpenAI", + "customWebApi", "aiServicesVision", and "aml". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchVectorizerKind + """ + + __mapping__: dict[str, _Model] = {} + vectorizer_name: str = rest_field(name="name", visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular vectorization method. Required.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of VectorSearchVectorizer. Required. Known values are: \"azureOpenAI\", \"customWebApi\", + \"aiServicesVision\", and \"aml\".""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AIServicesVisionVectorizer(VectorSearchVectorizer, discriminator="aiServicesVision"): + """Clears the identity property of a datasource. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar ai_services_vision_parameters: Contains the parameters specific to AI Services Vision + embedding vectorization. + :vartype ai_services_vision_parameters: + ~azure.search.documents.indexes.models.AIServicesVisionParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings for an image or text input at query time using the Azure + AI Services Vision Vectorize API. + :vartype kind: str or ~azure.search.documents.indexes.models.AI_SERVICES_VISION + """ + + ai_services_vision_parameters: Optional["_models.AIServicesVisionParameters"] = rest_field( + name="AIServicesVisionParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to AI Services Vision embedding vectorization.""" + kind: Literal[VectorSearchVectorizerKind.AI_SERVICES_VISION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings for an image or text input at query time using the Azure AI + Services Vision Vectorize API.""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + ai_services_vision_parameters: Optional["_models.AIServicesVisionParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AI_SERVICES_VISION # type: ignore + + +class AnalyzedTokenInfo(_Model): + """Information about a token returned by an analyzer. + + :ivar token: The token returned by the analyzer. Required. + :vartype token: str + :ivar start_offset: The index of the first character of the token in the input text. Required. + :vartype start_offset: int + :ivar end_offset: The index of the last character of the token in the input text. Required. + :vartype end_offset: int + :ivar position: The position of the token in the input text relative to other tokens. The first + token in the input text has position 0, the next has position 1, and so on. Depending on the + analyzer used, some tokens might have the same position, for example if they are synonyms of + each other. Required. + :vartype position: int + """ + + token: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The token returned by the analyzer. Required.""" + start_offset: int = rest_field(name="startOffset", visibility=["read", "create", "update", "delete", "query"]) + """The index of the first character of the token in the input text. Required.""" + end_offset: int = rest_field(name="endOffset", visibility=["read", "create", "update", "delete", "query"]) + """The index of the last character of the token in the input text. Required.""" + position: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The position of the token in the input text relative to other tokens. The first token in the + input text has position 0, the next has position 1, and so on. Depending on the analyzer used, + some tokens might have the same position, for example if they are synonyms of each other. + Required.""" + + @overload + def __init__( + self, + *, + token: str, + start_offset: int, + end_offset: int, + position: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AnalyzeRequest(_Model): + """Specifies some text and analysis components used to break that text into tokens. + + :ivar text: The text to break into tokens. Required. + :vartype text: str + :ivar analyzer: The name of the analyzer to use to break the given text. If this parameter is + not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are + mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", + "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar tokenizer: The name of the tokenizer to use to break the given text. If this parameter is + not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters are + mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", "letter", + "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", + "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". + :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName + :ivar normalizer: The name of the normalizer to use to normalize the given text. Known values + are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". + :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :ivar token_filters: An optional list of token filters to use when breaking the given text. + This parameter can only be set when using the tokenizer parameter. + :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] + :ivar char_filters: An optional list of character filters to use when breaking the given text. + This parameter can only be set when using the tokenizer parameter. + :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text to break into tokens. Required.""" + analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer to use to break the given text. If this parameter is not specified, + you must specify a tokenizer instead. The tokenizer and analyzer parameters are mutually + exclusive. Known values are: \"ar.microsoft\", \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", + \"eu.lucene\", \"bg.microsoft\", \"bg.lucene\", \"ca.microsoft\", \"ca.lucene\", + \"zh-Hans.microsoft\", \"zh-Hans.lucene\", \"zh-Hant.microsoft\", \"zh-Hant.lucene\", + \"hr.microsoft\", \"cs.microsoft\", \"cs.lucene\", \"da.microsoft\", \"da.lucene\", + \"nl.microsoft\", \"nl.lucene\", \"en.microsoft\", \"en.lucene\", \"et.microsoft\", + \"fi.microsoft\", \"fi.lucene\", \"fr.microsoft\", \"fr.lucene\", \"gl.lucene\", + \"de.microsoft\", \"de.lucene\", \"el.microsoft\", \"el.lucene\", \"gu.microsoft\", + \"he.microsoft\", \"hi.microsoft\", \"hi.lucene\", \"hu.microsoft\", \"hu.lucene\", + \"is.microsoft\", \"id.microsoft\", \"id.lucene\", \"ga.lucene\", \"it.microsoft\", + \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", \"kn.microsoft\", \"ko.microsoft\", + \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", \"lt.microsoft\", \"ml.microsoft\", + \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", \"no.lucene\", \"fa.lucene\", + \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", \"pt-BR.lucene\", \"pt-PT.microsoft\", + \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", \"ro.lucene\", \"ru.microsoft\", + \"ru.lucene\", \"sr-cyrillic.microsoft\", \"sr-latin.microsoft\", \"sk.microsoft\", + \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", \"sv.microsoft\", \"sv.lucene\", + \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", \"th.lucene\", \"tr.microsoft\", + \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", \"standard.lucene\", + \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", \"stop\", and + \"whitespace\".""" + tokenizer: Optional[Union[str, "_models.LexicalTokenizerName"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the tokenizer to use to break the given text. If this parameter is not specified, + you must specify an analyzer instead. The tokenizer and analyzer parameters are mutually + exclusive. Known values are: \"classic\", \"edgeNGram\", \"keyword_v2\", \"letter\", + \"lowercase\", \"microsoft_language_tokenizer\", \"microsoft_language_stemming_tokenizer\", + \"nGram\", \"path_hierarchy_v2\", \"pattern\", \"standard_v2\", \"uax_url_email\", and + \"whitespace\".""" + normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the normalizer to use to normalize the given text. Known values are: + \"asciifolding\", \"elision\", \"lowercase\", \"standard\", and \"uppercase\".""" + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """An optional list of token filters to use when breaking the given text. This parameter can only + be set when using the tokenizer parameter.""" + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """An optional list of character filters to use when breaking the given text. This parameter can + only be set when using the tokenizer parameter.""" + + @overload + def __init__( + self, + *, + text: str, + analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + tokenizer: Optional[Union[str, "_models.LexicalTokenizerName"]] = None, + normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AnalyzeResult(_Model): + """The result of testing an analyzer on text. + + :ivar tokens: The list of tokens returned by the analyzer specified in the request. Required. + :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] + """ + + tokens: list["_models.AnalyzedTokenInfo"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of tokens returned by the analyzer specified in the request. Required.""" + + @overload + def __init__( + self, + *, + tokens: list["_models.AnalyzedTokenInfo"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TokenFilter(_Model): + """Base type for token filters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AsciiFoldingTokenFilter, CjkBigramTokenFilter, CommonGramTokenFilter, + DictionaryDecompounderTokenFilter, EdgeNGramTokenFilter, ElisionTokenFilter, KeepTokenFilter, + KeywordMarkerTokenFilter, LengthTokenFilter, LimitTokenFilter, NGramTokenFilter, + PatternCaptureTokenFilter, PatternReplaceTokenFilter, PhoneticTokenFilter, ShingleTokenFilter, + SnowballTokenFilter, StemmerOverrideTokenFilter, StemmerTokenFilter, StopwordsTokenFilter, + SynonymTokenFilter, TruncateTokenFilter, UniqueTokenFilter, WordDelimiterTokenFilter + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the token filter. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AsciiFoldingTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.AsciiFoldingTokenFilter"): + """Converts alphabetic, numeric, and symbolic Unicode characters which are not in the first 127 + ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if such + equivalents exist. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar preserve_original: A value indicating whether the original token will be kept. Default is + false. + :vartype preserve_original: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.AsciiFoldingTokenFilter". + :vartype odata_type: str + """ + + preserve_original: Optional[bool] = rest_field( + name="preserveOriginal", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the original token will be kept. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.AsciiFoldingTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.AsciiFoldingTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + preserve_original: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.AsciiFoldingTokenFilter" # type: ignore + + +class AzureActiveDirectoryApplicationCredentials(_Model): # pylint: disable=name-too-long + """Credentials of a registered application created for your search service, used for authenticated + access to the encryption keys stored in Azure Key Vault. + + :ivar application_id: An AAD Application ID that was granted the required access permissions to + the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID + should not be confused with the Object ID for your AAD Application. Required. + :vartype application_id: str + :ivar application_secret: The authentication key of the specified AAD application. + :vartype application_secret: str + """ + + application_id: str = rest_field(name="applicationId", visibility=["read", "create", "update", "delete", "query"]) + """An AAD Application ID that was granted the required access permissions to the Azure Key Vault + that is to be used when encrypting your data at rest. The Application ID should not be confused + with the Object ID for your AAD Application. Required.""" + application_secret: Optional[str] = rest_field( + name="applicationSecret", visibility=["read", "create", "update", "delete", "query"] + ) + """The authentication key of the specified AAD application.""" + + @overload + def __init__( + self, + *, + application_id: str, + application_secret: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSource(_Model): + """Represents a knowledge source definition. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureBlobKnowledgeSource, SearchIndexKnowledgeSource + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", + "azureBlob", "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind + :ivar e_tag: The ETag of the agent. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + __mapping__: dict[str, _Model] = {} + name: str = rest_field(visibility=["read"]) + """The name of the knowledge source. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined description.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The type of the knowledge source. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the agent.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault.""" + + @overload + def __init__( + self, + *, + kind: str, + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureBlobKnowledgeSource(KnowledgeSource, discriminator="azureBlob"): + """Configuration for Azure Blob Storage knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the agent. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that read and ingest data from Azure Blob Storage to a + Search Index. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_BLOB + :ivar azure_blob_parameters: The type of the knowledge source. Required. + :vartype azure_blob_parameters: + ~azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters + """ + + kind: Literal[KnowledgeSourceKind.AZURE_BLOB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that read and ingest data from Azure Blob Storage to a Search + Index.""" + azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters" = rest_field( + name="azureBlobParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of the knowledge source. Required.""" + + @overload + def __init__( + self, + *, + azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters", + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.AZURE_BLOB # type: ignore + + +class AzureBlobKnowledgeSourceParameters(_Model): + """Parameters for Azure Blob Storage knowledge source. + + :ivar identity: An explicit identity to use for this knowledge source. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar connection_string: Key-based connection string or the ResourceId format if using a + managed identity. Required. + :vartype connection_string: str + :ivar container_name: The name of the blob storage container. Required. + :vartype container_name: str + :ivar folder_path: Optional folder path within the container. + :vartype folder_path: str + :ivar embedding_model: Optional vectorizer configuration for vectorizing content. + :vartype embedding_model: ~azure.search.documents.indexes.models.VectorSearchVectorizer + :ivar chat_completion_model: Optional chat completion model for image verbalization or context + extraction. + :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeAgentModel + :ivar ingestion_schedule: Optional schedule for data ingestion. + :vartype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule + :ivar created_resources: Resources created by the knowledge source. + :vartype created_resources: ~azure.search.documents.indexes.models.CreatedResources + :ivar disable_image_verbalization: Indicates whether image verbalization should be disabled. + :vartype disable_image_verbalization: bool + """ + + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An explicit identity to use for this knowledge source.""" + connection_string: str = rest_field( + name="connectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """Key-based connection string or the ResourceId format if using a managed identity. Required.""" + container_name: str = rest_field(name="containerName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the blob storage container. Required.""" + folder_path: Optional[str] = rest_field( + name="folderPath", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional folder path within the container.""" + embedding_model: Optional["_models.VectorSearchVectorizer"] = rest_field( + name="embeddingModel", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional vectorizer configuration for vectorizing content.""" + chat_completion_model: Optional["_models.KnowledgeAgentModel"] = rest_field( + name="chatCompletionModel", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional chat completion model for image verbalization or context extraction.""" + ingestion_schedule: Optional["_models.IndexingSchedule"] = rest_field( + name="ingestionSchedule", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional schedule for data ingestion.""" + created_resources: Optional["_models.CreatedResources"] = rest_field(name="createdResources", visibility=["read"]) + """Resources created by the knowledge source.""" + disable_image_verbalization: Optional[bool] = rest_field( + name="disableImageVerbalization", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether image verbalization should be disabled.""" + + @overload + def __init__( + self, + *, + connection_string: str, + container_name: str, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + folder_path: Optional[str] = None, + embedding_model: Optional["_models.VectorSearchVectorizer"] = None, + chat_completion_model: Optional["_models.KnowledgeAgentModel"] = None, + ingestion_schedule: Optional["_models.IndexingSchedule"] = None, + disable_image_verbalization: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureMachineLearningParameters(_Model): + """Specifies the properties for connecting to an AML vectorizer. + + :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of + the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. + Required. + :vartype scoring_uri: str + :ivar authentication_key: (Required for key authentication) The key for the AML service. + :vartype authentication_key: str + :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID + of the AML service. It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. + :vartype resource_id: str + :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the + API call. + :vartype timeout: ~datetime.timedelta + :ivar region: (Optional for token authentication). The region the AML service is deployed in. + :vartype region: str + :ivar model_name: The name of the embedding model from the Azure AI Foundry Catalog that is + deployed at the provided endpoint. Known values are: + "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", + "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", + "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", + "Cohere-embed-v3-english", and "Cohere-embed-v3-multilingual". + :vartype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName + """ + + scoring_uri: str = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) + """(Required for no authentication or key authentication) The scoring URI of the AML service to + which the JSON payload will be sent. Only the https URI scheme is allowed. Required.""" + authentication_key: Optional[str] = rest_field( + name="key", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for key authentication) The key for the AML service.""" + resource_id: Optional[str] = rest_field( + name="resourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for token authentication). The Azure Resource Manager resource ID of the AML service. + It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional) When specified, indicates the timeout for the http client making the API call.""" + region: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional for token authentication). The region the AML service is deployed in.""" + model_name: Optional[Union[str, "_models.AIFoundryModelCatalogName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model from the Azure AI Foundry Catalog that is deployed at the + provided endpoint. Known values are: \"OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32\", + \"OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336\", + \"Facebook-DinoV2-Image-Embeddings-ViT-Base\", \"Facebook-DinoV2-Image-Embeddings-ViT-Giant\", + \"Cohere-embed-v3-english\", and \"Cohere-embed-v3-multilingual\".""" + + @overload + def __init__( + self, + *, + scoring_uri: str, + authentication_key: Optional[str] = None, + resource_id: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + region: Optional[str] = None, + model_name: Optional[Union[str, "_models.AIFoundryModelCatalogName"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerSkill(_Model): + """Base type for skills. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureMachineLearningSkill, ChatCompletionSkill, WebApiSkill, AzureOpenAIEmbeddingSkill, + CustomEntityLookupSkill, EntityRecognitionSkill, KeyPhraseExtractionSkill, + LanguageDetectionSkill, MergeSkill, PIIDetectionSkill, SentimentSkill, SplitSkill, + TextTranslationSkill, EntityLinkingSkill, EntityRecognitionSkillV3, SentimentSkillV3, + ConditionalSkill, DocumentExtractionSkill, DocumentIntelligenceLayoutSkill, ShaperSkill, + ImageAnalysisSkill, OcrSkill, VisionVectorizeSkill + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the skill which uniquely identifies it within the skillset. A skill with no name + defined will be given a default name of its 1-based index in the skills array, prefixed with + the character '#'.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the skill which describes the inputs, outputs, and usage of the skill.""" + context: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Represents the level at which operations take place, such as the document root or document + content (for example, /document or /document/content). The default is /document.""" + inputs: list["_models.InputFieldMappingEntry"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Inputs of the skills could be a column in the source data set, or the output of an upstream + skill. Required.""" + outputs: list["_models.OutputFieldMappingEntry"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The output of a skill is either a field in a search index, or a value that can be consumed as + an input by another skill. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureMachineLearningSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.AmlSkill"): + """The AML skill allows you to extend AI enrichment with a custom Azure Machine Learning (AML) + model. Once an AML model is trained and deployed, an AML skill integrates it into AI + enrichment. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar scoring_uri: (Required for no authentication or key authentication) The scoring URI of + the AML service to which the JSON payload will be sent. Only the https URI scheme is allowed. + :vartype scoring_uri: str + :ivar authentication_key: (Required for key authentication) The key for the AML service. + :vartype authentication_key: str + :ivar resource_id: (Required for token authentication). The Azure Resource Manager resource ID + of the AML service. It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. + :vartype resource_id: str + :ivar timeout: (Optional) When specified, indicates the timeout for the http client making the + API call. + :vartype timeout: ~datetime.timedelta + :ivar region: (Optional for token authentication). The region the AML service is deployed in. + :vartype region: str + :ivar degree_of_parallelism: (Optional) When specified, indicates the number of calls the + indexer will make in parallel to the endpoint you have provided. You can decrease this value if + your endpoint is failing under too high of a request load, or raise it if your endpoint is able + to accept more requests and you would like an increase in the performance of the indexer. If + not set, a default value of 5 is used. The degreeOfParallelism can be set to a maximum of 10 + and a minimum of 1. + :vartype degree_of_parallelism: int + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Custom.AmlSkill". + :vartype odata_type: str + """ + + scoring_uri: Optional[str] = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) + """(Required for no authentication or key authentication) The scoring URI of the AML service to + which the JSON payload will be sent. Only the https URI scheme is allowed.""" + authentication_key: Optional[str] = rest_field( + name="key", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for key authentication) The key for the AML service.""" + resource_id: Optional[str] = rest_field( + name="resourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """(Required for token authentication). The Azure Resource Manager resource ID of the AML service. + It should be in the format + subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional) When specified, indicates the timeout for the http client making the API call.""" + region: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """(Optional for token authentication). The region the AML service is deployed in.""" + degree_of_parallelism: Optional[int] = rest_field( + name="degreeOfParallelism", visibility=["read", "create", "update", "delete", "query"] + ) + """(Optional) When specified, indicates the number of calls the indexer will make in parallel to + the endpoint you have provided. You can decrease this value if your endpoint is failing under + too high of a request load, or raise it if your endpoint is able to accept more requests and + you would like an increase in the performance of the indexer. If not set, a default value of 5 + is used. The degreeOfParallelism can be set to a maximum of 10 and a minimum of 1.""" + odata_type: Literal["#Microsoft.Skills.Custom.AmlSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Custom.AmlSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + scoring_uri: Optional[str] = None, + authentication_key: Optional[str] = None, + resource_id: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + region: Optional[str] = None, + degree_of_parallelism: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.AmlSkill" # type: ignore + + +class AzureMachineLearningVectorizer(VectorSearchVectorizer, discriminator="aml"): + """Specifies an Azure Machine Learning endpoint deployed via the Azure AI Foundry Model Catalog + for generating the vector embedding of a query string. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar aml_parameters: Specifies the properties of the AML vectorizer. + :vartype aml_parameters: ~azure.search.documents.indexes.models.AzureMachineLearningParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings using an Azure Machine Learning endpoint deployed via the + Azure AI Foundry Model Catalog at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.AML + """ + + aml_parameters: Optional["_models.AzureMachineLearningParameters"] = rest_field( + name="amlParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the properties of the AML vectorizer.""" + kind: Literal[VectorSearchVectorizerKind.AML] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings using an Azure Machine Learning endpoint deployed via the Azure + AI Foundry Model Catalog at query time.""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + aml_parameters: Optional["_models.AzureMachineLearningParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AML # type: ignore + + +class AzureOpenAIEmbeddingSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"): + """Allows you to generate a vector embedding for a given text input using the Azure OpenAI + resource. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar resource_url: The resource URI of the Azure OpenAI resource. + :vartype resource_url: str + :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. + :vartype deployment_name: str + :ivar api_key: API key of the designated Azure OpenAI resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", and + "text-embedding-3-small". + :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + :ivar dimensions: The number of dimensions the resulting output embeddings should have. Only + supported in text-embedding-3 and later models. + :vartype dimensions: int + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill". + :vartype odata_type: str + """ + + resource_url: Optional[str] = rest_field( + name="resourceUri", visibility=["read", "create", "update", "delete", "query"] + ) + """The resource URI of the Azure OpenAI resource.""" + deployment_name: Optional[str] = rest_field( + name="deploymentId", visibility=["read", "create", "update", "delete", "query"] + ) + """ID of the Azure OpenAI model deployment on the designated resource.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated Azure OpenAI resource.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections.""" + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model that is deployed at the provided deploymentId path. Known + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", and + \"text-embedding-3-small\".""" + dimensions: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of dimensions the resulting output embeddings should have. Only supported in + text-embedding-3 and later models.""" + odata_type: Literal["#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + resource_url: Optional[str] = None, + deployment_name: Optional[str] = None, + api_key: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + dimensions: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill" # type: ignore + + +class AzureOpenAiParameters(_Model): + """Specifies the parameters for connecting to the Azure OpenAI resource. + + :ivar resource_uri: The resource URI of the Azure OpenAI resource. Required. + :vartype resource_uri: str + :ivar deployment_id: ID of the Azure OpenAI model deployment on the designated resource. + Required. + :vartype deployment_id: str + :ivar api_key: API key of the designated Azure OpenAI resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :vartype auth_identity: str + :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", and + "text-embedding-3-small". + :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + :ivar authentication_method: The authentication method to use when connecting to the Azure + OpenAI resource. + :vartype authentication_method: str + """ + + resource_uri: str = rest_field(name="resourceUri", visibility=["read", "create", "update", "delete", "query"]) + """The resource URI of the Azure OpenAI resource. Required.""" + deployment_id: str = rest_field(name="deploymentId", visibility=["read", "create", "update", "delete", "query"]) + """ID of the Azure OpenAI model deployment on the designated resource. Required.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated Azure OpenAI resource.""" + auth_identity: Optional[str] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections.""" + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model that is deployed at the provided deploymentId path. Known + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", and + \"text-embedding-3-small\".""" + authentication_method: Optional[str] = rest_field( + name="authenticationMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The authentication method to use when connecting to the Azure OpenAI resource.""" + + @overload + def __init__( + self, + *, + resource_uri: str, + deployment_id: str, + api_key: Optional[str] = None, + auth_identity: Optional[str] = None, + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + authentication_method: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureOpenAITokenizerParameters(_Model): + """Azure OpenAI Tokenizer parameters. + + :ivar encoder_model_name: Only applies if the unit is set to azureOpenAITokens. Options include + 'R50k_base', 'P50k_base', 'P50k_edit' and 'CL100k_base'. The default value is 'CL100k_base'. + Known values are: "r50k_base", "p50k_base", "p50k_edit", and "cl100k_base". + :vartype encoder_model_name: str or + ~azure.search.documents.indexes.models.SplitSkillEncoderModelName + :ivar allowed_special_tokens: (Optional) Only applies if the unit is set to azureOpenAITokens. + This parameter defines a collection of special tokens that are permitted within the + tokenization process. + :vartype allowed_special_tokens: list[str] + """ + + encoder_model_name: Optional[Union[str, "_models.SplitSkillEncoderModelName"]] = rest_field( + name="encoderModelName", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applies if the unit is set to azureOpenAITokens. Options include 'R50k_base', 'P50k_base', + 'P50k_edit' and 'CL100k_base'. The default value is 'CL100k_base'. Known values are: + \"r50k_base\", \"p50k_base\", \"p50k_edit\", and \"cl100k_base\".""" + allowed_special_tokens: Optional[list[str]] = rest_field( + name="allowedSpecialTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """(Optional) Only applies if the unit is set to azureOpenAITokens. This parameter defines a + collection of special tokens that are permitted within the tokenization process.""" + + @overload + def __init__( + self, + *, + encoder_model_name: Optional[Union[str, "_models.SplitSkillEncoderModelName"]] = None, + allowed_special_tokens: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureOpenAIVectorizer(VectorSearchVectorizer, discriminator="azureOpenAI"): + """Specifies the Azure OpenAI resource used to vectorize a query string. + + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar parameters: Contains the parameters specific to Azure OpenAI embedding vectorization. + :vartype parameters: ~azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings using an Azure OpenAI resource at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_OPEN_AI + """ + + parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = rest_field( + name="azureOpenAIParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to Azure OpenAI embedding vectorization.""" + kind: Literal[VectorSearchVectorizerKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings using an Azure OpenAI resource at query time.""" + + @overload + def __init__( + self, + *, + vectorizer_name: str, + parameters: Optional["_models.AzureOpenAIVectorizerParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.AZURE_OPEN_AI # type: ignore + + +class AzureOpenAIVectorizerParameters(_Model): + """Specifies the parameters for connecting to the Azure OpenAI resource. + + :ivar resource_url: The resource URI of the Azure OpenAI resource. + :vartype resource_url: str + :ivar deployment_name: ID of the Azure OpenAI model deployment on the designated resource. + :vartype deployment_name: str + :ivar api_key: API key of the designated Azure OpenAI resource. + :vartype api_key: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", and + "text-embedding-3-small". + :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + """ + + resource_url: Optional[str] = rest_field( + name="resourceUri", visibility=["read", "create", "update", "delete", "query"] + ) + """The resource URI of the Azure OpenAI resource.""" + deployment_name: Optional[str] = rest_field( + name="deploymentId", visibility=["read", "create", "update", "delete", "query"] + ) + """ID of the Azure OpenAI model deployment on the designated resource.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key of the designated Azure OpenAI resource.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections.""" + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = rest_field( + name="modelName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the embedding model that is deployed at the provided deploymentId path. Known + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", and + \"text-embedding-3-small\".""" + + @overload + def __init__( + self, + *, + resource_url: Optional[str] = None, + deployment_name: Optional[str] = None, + api_key: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorSearchCompression(_Model): + """Contains configuration options specific to the compression method used during indexing or + querying. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + BinaryQuantizationCompression, ScalarQuantizationCompression + + :ivar compression_name: The name to associate with this particular configuration. Required. + :vartype compression_name: str + :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated + using compressed vectors are obtained, they will be reranked again by recalculating the + full-precision similarity scores. This will improve recall at the expense of latency. + :vartype rerank_with_original_vectors: bool + :ivar default_oversampling: Default oversampling factor. Oversampling will internally request + more documents (specified by this multiplier) in the initial search. This increases the set of + results that will be reranked using recomputed similarity scores from full-precision vectors. + Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when + rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. + :vartype default_oversampling: float + :ivar rescoring_options: Contains the options for rescoring. + :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions + :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the + vectors reduces the size of the vectors and the amount of data that needs to be transferred + during search. This can save storage cost and improve search performance at the expense of + recall. It should be only used for embeddings trained with Matryoshka Representation Learning + (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no + truncation. + :vartype truncation_dimension: int + :ivar kind: Type of VectorSearchCompression. Required. Known values are: "scalarQuantization" + and "binaryQuantization". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchCompressionKind + """ + + __mapping__: dict[str, _Model] = {} + compression_name: str = rest_field(name="name", visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular configuration. Required.""" + rerank_with_original_vectors: Optional[bool] = rest_field( + name="rerankWithOriginalVectors", visibility=["read", "create", "update", "delete", "query"] + ) + """If set to true, once the ordered set of results calculated using compressed vectors are + obtained, they will be reranked again by recalculating the full-precision similarity scores. + This will improve recall at the expense of latency.""" + default_oversampling: Optional[float] = rest_field( + name="defaultOversampling", visibility=["read", "create", "update", "delete", "query"] + ) + """Default oversampling factor. Oversampling will internally request more documents (specified by + this multiplier) in the initial search. This increases the set of results that will be reranked + using recomputed similarity scores from full-precision vectors. Minimum value is 1, meaning no + oversampling (1x). This parameter can only be set when rerankWithOriginalVectors is true. + Higher values improve recall at the expense of latency.""" + rescoring_options: Optional["_models.RescoringOptions"] = rest_field( + name="rescoringOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the options for rescoring.""" + truncation_dimension: Optional[int] = rest_field( + name="truncationDimension", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of dimensions to truncate the vectors to. Truncating the vectors reduces the size of + the vectors and the amount of data that needs to be transferred during search. This can save + storage cost and improve search performance at the expense of recall. It should be only used + for embeddings trained with Matryoshka Representation Learning (MRL) such as OpenAI + text-embedding-3-large (small). The default value is null, which means no truncation.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of VectorSearchCompression. Required. Known values are: \"scalarQuantization\" and + \"binaryQuantization\".""" + + @overload + def __init__( + self, + *, + compression_name: str, + kind: str, + rerank_with_original_vectors: Optional[bool] = None, + default_oversampling: Optional[float] = None, + rescoring_options: Optional["_models.RescoringOptions"] = None, + truncation_dimension: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BinaryQuantizationCompression(VectorSearchCompression, discriminator="binaryQuantization"): + """Contains configuration options specific to the binary quantization compression method used + during indexing and querying. + + :ivar compression_name: The name to associate with this particular configuration. Required. + :vartype compression_name: str + :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated + using compressed vectors are obtained, they will be reranked again by recalculating the + full-precision similarity scores. This will improve recall at the expense of latency. + :vartype rerank_with_original_vectors: bool + :ivar default_oversampling: Default oversampling factor. Oversampling will internally request + more documents (specified by this multiplier) in the initial search. This increases the set of + results that will be reranked using recomputed similarity scores from full-precision vectors. + Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when + rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. + :vartype default_oversampling: float + :ivar rescoring_options: Contains the options for rescoring. + :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions + :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the + vectors reduces the size of the vectors and the amount of data that needs to be transferred + during search. This can save storage cost and improve search performance at the expense of + recall. It should be only used for embeddings trained with Matryoshka Representation Learning + (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no + truncation. + :vartype truncation_dimension: int + :ivar kind: The name of the kind of compression method being configured for use with vector + search. Required. Binary Quantization, a type of compression method. In binary quantization, + the original vectors values are compressed to the narrower binary type by discretizing and + representing each component of a vector using binary values, thereby reducing the overall data + size. + :vartype kind: str or ~azure.search.documents.indexes.models.BINARY_QUANTIZATION + """ + + kind: Literal[VectorSearchCompressionKind.BINARY_QUANTIZATION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of compression method being configured for use with vector search. + Required. Binary Quantization, a type of compression method. In binary quantization, the + original vectors values are compressed to the narrower binary type by discretizing and + representing each component of a vector using binary values, thereby reducing the overall data + size.""" + + @overload + def __init__( + self, + *, + compression_name: str, + rerank_with_original_vectors: Optional[bool] = None, + default_oversampling: Optional[float] = None, + rescoring_options: Optional["_models.RescoringOptions"] = None, + truncation_dimension: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchCompressionKind.BINARY_QUANTIZATION # type: ignore + + +class SimilarityAlgorithm(_Model): + """Base type for similarity algorithms. Similarity algorithms are used to calculate scores that + tie queries to documents. The higher the score, the more relevant the document is to that + specific query. Those scores are used to rank the search results. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + BM25SimilarityAlgorithm, ClassicSimilarityAlgorithm + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BM25SimilarityAlgorithm(SimilarityAlgorithm, discriminator="#Microsoft.Azure.Search.BM25Similarity"): + """Ranking function based on the Okapi BM25 similarity algorithm. BM25 is a TF-IDF-like algorithm + that includes length normalization (controlled by the 'b' parameter) as well as term frequency + saturation (controlled by the 'k1' parameter). + + :ivar k1: This property controls the scaling function between the term frequency of each + matching terms and the final relevance score of a document-query pair. By default, a value of + 1.2 is used. A value of 0.0 means the score does not scale with an increase in term frequency. + :vartype k1: float + :ivar b: This property controls how the length of a document affects the relevance score. By + default, a value of 0.75 is used. A value of 0.0 means no length normalization is applied, + while a value of 1.0 means the score is fully normalized by the length of the document. + :vartype b: float + :ivar odata_type: The discriminator for derived types. Required. Default value is + "#Microsoft.Azure.Search.BM25Similarity". + :vartype odata_type: str + """ + + k1: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This property controls the scaling function between the term frequency of each matching terms + and the final relevance score of a document-query pair. By default, a value of 1.2 is used. A + value of 0.0 means the score does not scale with an increase in term frequency.""" + b: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This property controls how the length of a document affects the relevance score. By default, a + value of 0.75 is used. A value of 0.0 means no length normalization is applied, while a value + of 1.0 means the score is fully normalized by the length of the document.""" + odata_type: Literal["#Microsoft.Azure.Search.BM25Similarity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator for derived types. Required. Default value is + \"#Microsoft.Azure.Search.BM25Similarity\".""" + + @overload + def __init__( + self, + *, + k1: Optional[float] = None, + b: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.BM25Similarity" # type: ignore + + +class CharFilter(_Model): + """Base type for character filters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + MappingCharFilter, PatternReplaceCharFilter + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the char filter. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionCommonModelParameters(_Model): + """Common language model parameters for Chat Completions. If omitted, default values are used. + + :ivar model_name: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not + specified. + :vartype model_name: str + :ivar frequency_penalty: A float in the range [-2,2] that reduces or increases likelihood of + repeated tokens. Default is 0. + :vartype frequency_penalty: float + :ivar presence_penalty: A float in the range [-2,2] that penalizes new tokens based on their + existing presence. Default is 0. + :vartype presence_penalty: float + :ivar max_tokens: Maximum number of tokens to generate. + :vartype max_tokens: int + :ivar temperature: Sampling temperature. Default is 0.7. + :vartype temperature: float + :ivar seed: Random seed for controlling deterministic outputs. If omitted, randomization is + used. + :vartype seed: int + :ivar stop: List of stop sequences that will cut off text generation. Default is none. + :vartype stop: list[str] + """ + + model_name: Optional[str] = rest_field(name="modelName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified.""" + frequency_penalty: Optional[float] = rest_field( + name="frequencyPenalty", visibility=["read", "create", "update", "delete", "query"] + ) + """A float in the range [-2,2] that reduces or increases likelihood of repeated tokens. Default is + 0.""" + presence_penalty: Optional[float] = rest_field( + name="presencePenalty", visibility=["read", "create", "update", "delete", "query"] + ) + """A float in the range [-2,2] that penalizes new tokens based on their existing presence. Default + is 0.""" + max_tokens: Optional[int] = rest_field(name="maxTokens", visibility=["read", "create", "update", "delete", "query"]) + """Maximum number of tokens to generate.""" + temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sampling temperature. Default is 0.7.""" + seed: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Random seed for controlling deterministic outputs. If omitted, randomization is used.""" + stop: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """List of stop sequences that will cut off text generation. Default is none.""" + + @overload + def __init__( + self, + *, + model_name: Optional[str] = None, + frequency_penalty: Optional[float] = None, + presence_penalty: Optional[float] = None, + max_tokens: Optional[int] = None, + temperature: Optional[float] = None, + seed: Optional[int] = None, + stop: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionResponseFormat(_Model): + """Determines how the language model's response should be serialized. Defaults to 'text'. + + :ivar type: Specifies how the LLM should format the response. Known values are: "text", + "jsonObject", and "jsonSchema". + :vartype type: str or ~azure.search.documents.indexes.models.ChatCompletionResponseFormatType + :ivar json_schema_properties: An open dictionary for extended properties. Required if 'type' == + 'json_schema'. + :vartype json_schema_properties: + ~azure.search.documents.indexes.models.ChatCompletionSchemaProperties + """ + + type: Optional[Union[str, "_models.ChatCompletionResponseFormatType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies how the LLM should format the response. Known values are: \"text\", \"jsonObject\", + and \"jsonSchema\".""" + json_schema_properties: Optional["_models.ChatCompletionSchemaProperties"] = rest_field( + name="jsonSchemaProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """An open dictionary for extended properties. Required if 'type' == 'json_schema'.""" + + @overload + def __init__( + self, + *, + type: Optional[Union[str, "_models.ChatCompletionResponseFormatType"]] = None, + json_schema_properties: Optional["_models.ChatCompletionSchemaProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionSchema(_Model): + """Object defining the custom schema the model will use to structure its output. + + :ivar type: Type of schema representation. Usually 'object'. Default is 'object'. + :vartype type: str + :ivar properties: A JSON-formatted string that defines the output schema's properties and + constraints for the model. + :vartype properties: str + :ivar required: An array of the property names that are required to be part of the model's + response. + :vartype required: list[str] + :ivar additional_properties: Controls whether it is allowable for an object to contain + additional keys / values that were not defined in the JSON Schema. Default is false. + :vartype additional_properties: bool + """ + + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type of schema representation. Usually 'object'. Default is 'object'.""" + properties: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A JSON-formatted string that defines the output schema's properties and constraints for the + model.""" + required: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An array of the property names that are required to be part of the model's response.""" + additional_properties: Optional[bool] = rest_field( + name="additionalProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls whether it is allowable for an object to contain additional keys / values that were + not defined in the JSON Schema. Default is false.""" + + @overload + def __init__( + self, + *, + type: Optional[str] = None, + properties: Optional[str] = None, + required: Optional[list[str]] = None, + additional_properties: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionSchemaProperties(_Model): + """Properties for JSON schema response format. + + :ivar name: Name of the json schema the model will adhere to. + :vartype name: str + :ivar description: Description of the json schema the model will adhere to. + :vartype description: str + :ivar strict: Whether or not the model's response should use structured outputs. Default is + true. + :vartype strict: bool + :ivar schema: The schema definition. + :vartype schema: ~azure.search.documents.indexes.models.ChatCompletionSchema + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the json schema the model will adhere to.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description of the json schema the model will adhere to.""" + strict: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether or not the model's response should use structured outputs. Default is true.""" + schema: Optional["_models.ChatCompletionSchema"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The schema definition.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + strict: Optional[bool] = None, + schema: Optional["_models.ChatCompletionSchema"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChatCompletionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.ChatCompletionSkill"): + """A skill that calls a language model via Azure AI Foundry's Chat Completions endpoint. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar uri: The url for the Web API. Required. + :vartype uri: str + :ivar http_headers: The headers required to make the http request. + :vartype http_headers: ~azure.search.documents.indexes.models.WebApiHttpHeaders + :ivar http_method: The method for the http request. + :vartype http_method: str + :ivar timeout: The desired timeout for the request. Default is 30 seconds. + :vartype timeout: ~datetime.timedelta + :ivar batch_size: The desired batch size which indicates number of documents. + :vartype batch_size: int + :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web + API. + :vartype degree_of_parallelism: int + :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure + function or some other application that provides the transformations. + :vartype auth_resource_id: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot be + specified at the same time. + :vartype api_key: str + :ivar common_model_parameters: Common language model parameters that customers can tweak. If + omitted, reasonable defaults will be applied. + :vartype common_model_parameters: + ~azure.search.documents.indexes.models.ChatCompletionCommonModelParameters + :ivar extra_parameters: Open-type dictionary for model-specific parameters that should be + appended to the chat completions call. Follows Azure AI Foundry's extensibility pattern. + :vartype extra_parameters: dict[str, any] + :ivar extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. Default + is 'error'. Known values are: "passThrough", "drop", and "error". + :vartype extra_parameters_behavior: str or + ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior + :ivar response_format: Determines how the LLM should format its response. Defaults to 'text' + response type. + :vartype response_format: ~azure.search.documents.indexes.models.ChatCompletionResponseFormat + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Custom.ChatCompletionSkill". + :vartype odata_type: str + """ + + uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url for the Web API. Required.""" + http_headers: Optional["_models.WebApiHttpHeaders"] = rest_field( + name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """The headers required to make the http request.""" + http_method: Optional[str] = rest_field( + name="httpMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The method for the http request.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The desired timeout for the request. Default is 30 seconds.""" + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) + """The desired batch size which indicates number of documents.""" + degree_of_parallelism: Optional[int] = rest_field( + name="degreeOfParallelism", visibility=["read", "create", "update", "delete", "query"] + ) + """If set, the number of parallel calls that can be made to the Web API.""" + auth_resource_id: Optional[str] = rest_field( + name="authResourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """Applies to custom skills that connect to external code in an Azure function or some other + application that provides the transformations.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections.""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """API key for authenticating to the model. Both apiKey and authIdentity cannot be specified at + the same time.""" + common_model_parameters: Optional["_models.ChatCompletionCommonModelParameters"] = rest_field( + name="commonModelParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Common language model parameters that customers can tweak. If omitted, reasonable defaults will + be applied.""" + extra_parameters: Optional[dict[str, Any]] = rest_field( + name="extraParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Open-type dictionary for model-specific parameters that should be appended to the chat + completions call. Follows Azure AI Foundry's extensibility pattern.""" + extra_parameters_behavior: Optional[Union[str, "_models.ChatCompletionExtraParametersBehavior"]] = rest_field( + name="extraParametersBehavior", visibility=["read", "create", "update", "delete", "query"] + ) + """How extra parameters are handled by Azure AI Foundry. Default is 'error'. Known values are: + \"passThrough\", \"drop\", and \"error\".""" + response_format: Optional["_models.ChatCompletionResponseFormat"] = rest_field( + name="responseFormat", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines how the LLM should format its response. Defaults to 'text' response type.""" + odata_type: Literal["#Microsoft.Skills.Custom.ChatCompletionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Custom.ChatCompletionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + uri: str, + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + http_headers: Optional["_models.WebApiHttpHeaders"] = None, + http_method: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + batch_size: Optional[int] = None, + degree_of_parallelism: Optional[int] = None, + auth_resource_id: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + api_key: Optional[str] = None, + common_model_parameters: Optional["_models.ChatCompletionCommonModelParameters"] = None, + extra_parameters: Optional[dict[str, Any]] = None, + extra_parameters_behavior: Optional[Union[str, "_models.ChatCompletionExtraParametersBehavior"]] = None, + response_format: Optional["_models.ChatCompletionResponseFormat"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.ChatCompletionSkill" # type: ignore + + +class CjkBigramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.CjkBigramTokenFilter"): + """Forms bigrams of CJK terms that are generated from the standard tokenizer. This token filter is + implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar ignore_scripts: The scripts to ignore. + :vartype ignore_scripts: list[str or + ~azure.search.documents.indexes.models.CjkBigramTokenFilterScripts] + :ivar output_unigrams: A value indicating whether to output both unigrams and bigrams (if + true), or just bigrams (if false). Default is false. + :vartype output_unigrams: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.CjkBigramTokenFilter". + :vartype odata_type: str + """ + + ignore_scripts: Optional[list[Union[str, "_models.CjkBigramTokenFilterScripts"]]] = rest_field( + name="ignoreScripts", visibility=["read", "create", "update", "delete", "query"] + ) + """The scripts to ignore.""" + output_unigrams: Optional[bool] = rest_field( + name="outputUnigrams", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to output both unigrams and bigrams (if true), or just bigrams (if + false). Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.CjkBigramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.CjkBigramTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + ignore_scripts: Optional[list[Union[str, "_models.CjkBigramTokenFilterScripts"]]] = None, + output_unigrams: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CjkBigramTokenFilter" # type: ignore + + +class ClassicSimilarityAlgorithm(SimilarityAlgorithm, discriminator="#Microsoft.Azure.Search.ClassicSimilarity"): + """Legacy similarity algorithm which uses the Lucene TFIDFSimilarity implementation of TF-IDF. + This variation of TF-IDF introduces static document length normalization as well as + coordinating factors that penalize documents that only partially match the searched queries. + + :ivar odata_type: The discriminator for derived types. Required. Default value is + "#Microsoft.Azure.Search.ClassicSimilarity". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.ClassicSimilarity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator for derived types. Required. Default value is + \"#Microsoft.Azure.Search.ClassicSimilarity\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ClassicSimilarity" # type: ignore + + +class LexicalTokenizer(_Model): + """Base type for tokenizers. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ClassicTokenizer, EdgeNGramTokenizer, KeywordTokenizer, MicrosoftLanguageStemmingTokenizer, + MicrosoftLanguageTokenizer, NGramTokenizer, PathHierarchyTokenizer, PatternTokenizer, + LuceneStandardTokenizer, UaxUrlEmailTokenizer + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the tokenizer. It must only contain letters, digits, spaces, dashes or underscores, + can only start and end with alphanumeric characters, and is limited to 128 characters. + Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ClassicTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.ClassicTokenizer"): + """Grammar-based tokenizer that is suitable for processing most European-language documents. This + tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.ClassicTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.ClassicTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.ClassicTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ClassicTokenizer" # type: ignore + + +class CognitiveServicesAccountKey( + CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.CognitiveServicesByKey" +): + """The multi-region account key of an Azure AI service resource that's attached to a skillset. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar key: The key used to provision the Azure AI service resource attached to a skillset. + Required. + :vartype key: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.CognitiveServicesByKey". + :vartype odata_type: str + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key used to provision the Azure AI service resource attached to a skillset. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.CognitiveServicesByKey"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.CognitiveServicesByKey\".""" + + @overload + def __init__( + self, + *, + key: str, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CognitiveServicesByKey" # type: ignore + + +class CommonGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.CommonGramTokenFilter"): + """Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed + too, with bigrams overlaid. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar common_words: The set of common words. Required. + :vartype common_words: list[str] + :ivar ignore_case: A value indicating whether common words matching will be case insensitive. + Default is false. + :vartype ignore_case: bool + :ivar use_query_mode: A value that indicates whether the token filter is in query mode. When in + query mode, the token filter generates bigrams and then removes common words and single terms + followed by a common word. Default is false. + :vartype use_query_mode: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.CommonGramTokenFilter". + :vartype odata_type: str + """ + + common_words: list[str] = rest_field(name="commonWords", visibility=["read", "create", "update", "delete", "query"]) + """The set of common words. Required.""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether common words matching will be case insensitive. Default is false.""" + use_query_mode: Optional[bool] = rest_field( + name="queryMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that indicates whether the token filter is in query mode. When in query mode, the token + filter generates bigrams and then removes common words and single terms followed by a common + word. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.CommonGramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.CommonGramTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + common_words: list[str], + ignore_case: Optional[bool] = None, + use_query_mode: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CommonGramTokenFilter" # type: ignore + + +class ConditionalSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.ConditionalSkill"): + """A skill that enables scenarios that require a Boolean operation to determine the data to assign + to an output. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.ConditionalSkill". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Skills.Util.ConditionalSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.ConditionalSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.ConditionalSkill" # type: ignore + + +class CorsOptions(_Model): + """Defines options to control Cross-Origin Resource Sharing (CORS) for an index. + + :ivar allowed_origins: The list of origins from which JavaScript code will be granted access to + your index. Can contain a list of hosts of the form + {protocol}://{fully-qualified-domain-name}[:{port#}], or a single '*' to allow all origins (not + recommended). Required. + :vartype allowed_origins: list[str] + :ivar max_age_in_seconds: The duration for which browsers should cache CORS preflight + responses. Defaults to 5 minutes. + :vartype max_age_in_seconds: int + """ + + allowed_origins: list[str] = rest_field( + name="allowedOrigins", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of origins from which JavaScript code will be granted access to your index. Can + contain a list of hosts of the form {protocol}://{fully-qualified-domain-name}[:{port#}], or a + single '*' to allow all origins (not recommended). Required.""" + max_age_in_seconds: Optional[int] = rest_field( + name="maxAgeInSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The duration for which browsers should cache CORS preflight responses. Defaults to 5 minutes.""" + + @overload + def __init__( + self, + *, + allowed_origins: list[str], + max_age_in_seconds: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreatedResources(_Model): + """Resources created by the knowledge source. Keys represent resource types (e.g., 'datasource', + 'indexer', 'skillset', 'index') and values represent resource names. + + """ + + +class LexicalAnalyzer(_Model): + """Base type for analyzers. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + CustomAnalyzer, PatternAnalyzer, LuceneStandardAnalyzer, StopAnalyzer + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the analyzer. It must only contain letters, digits, spaces, dashes or underscores, + can only start and end with alphanumeric characters, and is limited to 128 characters. + Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.CustomAnalyzer"): + """Allows you to take control over the process of converting text into indexable/searchable + tokens. It's a user-defined configuration consisting of a single predefined tokenizer and one + or more filters. The tokenizer is responsible for breaking text into tokens, and the filters + for modifying tokens emitted by the tokenizer. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar tokenizer: The name of the tokenizer to use to divide continuous text into a sequence of + tokens, such as breaking a sentence into words. Required. Known values are: "classic", + "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", + "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", + "standard_v2", "uax_url_email", and "whitespace". + :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName + :ivar token_filters: A list of token filters used to filter out or modify the tokens generated + by a tokenizer. For example, you can specify a lowercase filter that converts all characters to + lowercase. The filters are run in the order in which they are listed. + :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] + :ivar char_filters: A list of character filters used to prepare input text before it is + processed by the tokenizer. For instance, they can replace certain characters or symbols. The + filters are run in the order in which they are listed. + :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.CustomAnalyzer". + :vartype odata_type: str + """ + + tokenizer: Union[str, "_models.LexicalTokenizerName"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the tokenizer to use to divide continuous text into a sequence of tokens, such as + breaking a sentence into words. Required. Known values are: \"classic\", \"edgeNGram\", + \"keyword_v2\", \"letter\", \"lowercase\", \"microsoft_language_tokenizer\", + \"microsoft_language_stemming_tokenizer\", \"nGram\", \"path_hierarchy_v2\", \"pattern\", + \"standard_v2\", \"uax_url_email\", and \"whitespace\".""" + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of token filters used to filter out or modify the tokens generated by a tokenizer. For + example, you can specify a lowercase filter that converts all characters to lowercase. The + filters are run in the order in which they are listed.""" + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of character filters used to prepare input text before it is processed by the tokenizer. + For instance, they can replace certain characters or symbols. The filters are run in the order + in which they are listed.""" + odata_type: Literal["#Microsoft.Azure.Search.CustomAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.CustomAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + tokenizer: Union[str, "_models.LexicalTokenizerName"], + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CustomAnalyzer" # type: ignore + + +class CustomEntity(_Model): + """An object that contains information about the matches that were found, and related metadata. + + :ivar name: The top-level entity descriptor. Matches in the skill output will be grouped by + this name, and it should represent the "normalized" form of the text being found. Required. + :vartype name: str + :ivar description: This field can be used as a passthrough for custom metadata about the + matched text(s). The value of this field will appear with every match of its entity in the + skill output. + :vartype description: str + :ivar type: This field can be used as a passthrough for custom metadata about the matched + text(s). The value of this field will appear with every match of its entity in the skill + output. + :vartype type: str + :ivar subtype: This field can be used as a passthrough for custom metadata about the matched + text(s). The value of this field will appear with every match of its entity in the skill + output. + :vartype subtype: str + :ivar id: This field can be used as a passthrough for custom metadata about the matched + text(s). The value of this field will appear with every match of its entity in the skill + output. + :vartype id: str + :ivar case_sensitive: Defaults to false. Boolean value denoting whether comparisons with the + entity name should be sensitive to character casing. Sample case insensitive matches of + "Microsoft" could be: microsoft, microSoft, MICROSOFT. + :vartype case_sensitive: bool + :ivar accent_sensitive: Defaults to false. Boolean value denoting whether comparisons with the + entity name should be sensitive to accent. + :vartype accent_sensitive: bool + :ivar fuzzy_edit_distance: Defaults to 0. Maximum value of 5. Denotes the acceptable number of + divergent characters that would still constitute a match with the entity name. The smallest + possible fuzziness for any given match is returned. For instance, if the edit distance is set + to 3, "Windows10" would still match "Windows", "Windows10" and "Windows 7". When case + sensitivity is set to false, case differences do NOT count towards fuzziness tolerance, but + otherwise do. + :vartype fuzzy_edit_distance: int + :ivar default_case_sensitive: Changes the default case sensitivity value for this entity. It be + used to change the default value of all aliases caseSensitive values. + :vartype default_case_sensitive: bool + :ivar default_accent_sensitive: Changes the default accent sensitivity value for this entity. + It be used to change the default value of all aliases accentSensitive values. + :vartype default_accent_sensitive: bool + :ivar default_fuzzy_edit_distance: Changes the default fuzzy edit distance value for this + entity. It can be used to change the default value of all aliases fuzzyEditDistance values. + :vartype default_fuzzy_edit_distance: int + :ivar aliases: An array of complex objects that can be used to specify alternative spellings or + synonyms to the root entity name. + :vartype aliases: list[~azure.search.documents.indexes.models.CustomEntityAlias] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The top-level entity descriptor. Matches in the skill output will be grouped by this name, and + it should represent the \"normalized\" form of the text being found. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + subtype: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """This field can be used as a passthrough for custom metadata about the matched text(s). The + value of this field will appear with every match of its entity in the skill output.""" + case_sensitive: Optional[bool] = rest_field( + name="caseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Defaults to false. Boolean value denoting whether comparisons with the entity name should be + sensitive to character casing. Sample case insensitive matches of \"Microsoft\" could be: + microsoft, microSoft, MICROSOFT.""" + accent_sensitive: Optional[bool] = rest_field( + name="accentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Defaults to false. Boolean value denoting whether comparisons with the entity name should be + sensitive to accent.""" + fuzzy_edit_distance: Optional[int] = rest_field( + name="fuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """Defaults to 0. Maximum value of 5. Denotes the acceptable number of divergent characters that + would still constitute a match with the entity name. The smallest possible fuzziness for any + given match is returned. For instance, if the edit distance is set to 3, \"Windows10\" would + still match \"Windows\", \"Windows10\" and \"Windows 7\". When case sensitivity is set to + false, case differences do NOT count towards fuzziness tolerance, but otherwise do.""" + default_case_sensitive: Optional[bool] = rest_field( + name="defaultCaseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Changes the default case sensitivity value for this entity. It be used to change the default + value of all aliases caseSensitive values.""" + default_accent_sensitive: Optional[bool] = rest_field( + name="defaultAccentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Changes the default accent sensitivity value for this entity. It be used to change the default + value of all aliases accentSensitive values.""" + default_fuzzy_edit_distance: Optional[int] = rest_field( + name="defaultFuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """Changes the default fuzzy edit distance value for this entity. It can be used to change the + default value of all aliases fuzzyEditDistance values.""" + aliases: Optional[list["_models.CustomEntityAlias"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An array of complex objects that can be used to specify alternative spellings or synonyms to + the root entity name.""" + + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + type: Optional[str] = None, + subtype: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + case_sensitive: Optional[bool] = None, + accent_sensitive: Optional[bool] = None, + fuzzy_edit_distance: Optional[int] = None, + default_case_sensitive: Optional[bool] = None, + default_accent_sensitive: Optional[bool] = None, + default_fuzzy_edit_distance: Optional[int] = None, + aliases: Optional[list["_models.CustomEntityAlias"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomEntityAlias(_Model): + """A complex object that can be used to specify alternative spellings or synonyms to the root + entity name. + + :ivar text: The text of the alias. Required. + :vartype text: str + :ivar case_sensitive: Determine if the alias is case sensitive. + :vartype case_sensitive: bool + :ivar accent_sensitive: Determine if the alias is accent sensitive. + :vartype accent_sensitive: bool + :ivar fuzzy_edit_distance: Determine the fuzzy edit distance of the alias. + :vartype fuzzy_edit_distance: int + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text of the alias. Required.""" + case_sensitive: Optional[bool] = rest_field( + name="caseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Determine if the alias is case sensitive.""" + accent_sensitive: Optional[bool] = rest_field( + name="accentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """Determine if the alias is accent sensitive.""" + fuzzy_edit_distance: Optional[int] = rest_field( + name="fuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """Determine the fuzzy edit distance of the alias.""" + + @overload + def __init__( + self, + *, + text: str, + case_sensitive: Optional[bool] = None, + accent_sensitive: Optional[bool] = None, + fuzzy_edit_distance: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomEntityLookupSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.CustomEntityLookupSkill"): + """A skill looks for text from a custom, user-defined list of words and phrases. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "da", "de", "en", "es", "fi", "fr", "it", "ko", and "pt". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage + :ivar entities_definition_uri: Path to a JSON or CSV file containing all the target text to + match against. This entity definition is read at the beginning of an indexer run. Any updates + to this file during an indexer run will not take effect until subsequent runs. This config must + be accessible over HTTPS. + :vartype entities_definition_uri: str + :ivar inline_entities_definition: The inline CustomEntity definition. + :vartype inline_entities_definition: list[~azure.search.documents.indexes.models.CustomEntity] + :ivar global_default_case_sensitive: A global flag for CaseSensitive. If CaseSensitive is not + set in CustomEntity, this value will be the default value. + :vartype global_default_case_sensitive: bool + :ivar global_default_accent_sensitive: A global flag for AccentSensitive. If AccentSensitive is + not set in CustomEntity, this value will be the default value. + :vartype global_default_accent_sensitive: bool + :ivar global_default_fuzzy_edit_distance: A global flag for FuzzyEditDistance. If + FuzzyEditDistance is not set in CustomEntity, this value will be the default value. + :vartype global_default_fuzzy_edit_distance: int + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.CustomEntityLookupSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.CustomEntityLookupSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"da\", + \"de\", \"en\", \"es\", \"fi\", \"fr\", \"it\", \"ko\", and \"pt\".""" + entities_definition_uri: Optional[str] = rest_field( + name="entitiesDefinitionUri", visibility=["read", "create", "update", "delete", "query"] + ) + """Path to a JSON or CSV file containing all the target text to match against. This entity + definition is read at the beginning of an indexer run. Any updates to this file during an + indexer run will not take effect until subsequent runs. This config must be accessible over + HTTPS.""" + inline_entities_definition: Optional[list["_models.CustomEntity"]] = rest_field( + name="inlineEntitiesDefinition", visibility=["read", "create", "update", "delete", "query"] + ) + """The inline CustomEntity definition.""" + global_default_case_sensitive: Optional[bool] = rest_field( + name="globalDefaultCaseSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """A global flag for CaseSensitive. If CaseSensitive is not set in CustomEntity, this value will + be the default value.""" + global_default_accent_sensitive: Optional[bool] = rest_field( + name="globalDefaultAccentSensitive", visibility=["read", "create", "update", "delete", "query"] + ) + """A global flag for AccentSensitive. If AccentSensitive is not set in CustomEntity, this value + will be the default value.""" + global_default_fuzzy_edit_distance: Optional[int] = rest_field( + name="globalDefaultFuzzyEditDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """A global flag for FuzzyEditDistance. If FuzzyEditDistance is not set in CustomEntity, this + value will be the default value.""" + odata_type: Literal["#Microsoft.Skills.Text.CustomEntityLookupSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.CustomEntityLookupSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.CustomEntityLookupSkillLanguage"]] = None, + entities_definition_uri: Optional[str] = None, + inline_entities_definition: Optional[list["_models.CustomEntity"]] = None, + global_default_case_sensitive: Optional[bool] = None, + global_default_accent_sensitive: Optional[bool] = None, + global_default_fuzzy_edit_distance: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.CustomEntityLookupSkill" # type: ignore + + +class LexicalNormalizer(_Model): + """Base type for normalizers. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + CustomNormalizer + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the char filter. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required.""" + + @overload + def __init__( + self, + *, + odata_type: str, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomNormalizer(LexicalNormalizer, discriminator="#Microsoft.Azure.Search.CustomNormalizer"): + """Allows you to configure normalization for filterable, sortable, and facetable fields, which by + default operate with strict matching. This is a user-defined configuration consisting of at + least one or more filters, which modify the token that is stored. + + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar token_filters: A list of token filters used to filter out or modify the input token. For + example, you can specify a lowercase filter that converts all characters to lowercase. The + filters are run in the order in which they are listed. + :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] + :ivar char_filters: A list of character filters used to prepare input text before it is + processed. For instance, they can replace certain characters or symbols. The filters are run in + the order in which they are listed. + :vartype char_filters: list[str or ~azure.search.documents.indexes.models.CharFilterName] + :ivar odata_type: A URI fragment specifying the type of normalizer. Required. Default value is + "#Microsoft.Azure.Search.CustomNormalizer". + :vartype odata_type: str + """ + + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of token filters used to filter out or modify the input token. For example, you can + specify a lowercase filter that converts all characters to lowercase. The filters are run in + the order in which they are listed.""" + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of character filters used to prepare input text before it is processed. For instance, + they can replace certain characters or symbols. The filters are run in the order in which they + are listed.""" + odata_type: Literal["#Microsoft.Azure.Search.CustomNormalizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of normalizer. Required. Default value is + \"#Microsoft.Azure.Search.CustomNormalizer\".""" + + @overload + def __init__( + self, + *, + name: str, + token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, + char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.CustomNormalizer" # type: ignore + + +class DataChangeDetectionPolicy(_Model): + """Base type for data change detection policies. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + HighWaterMarkChangeDetectionPolicy, SqlIntegratedChangeTrackingPolicy + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataDeletionDetectionPolicy(_Model): + """Base type for data deletion detection policies. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + NativeBlobSoftDeleteDeletionDetectionPolicy, SoftDeleteColumnDeletionDetectionPolicy + + :ivar odata_type: The discriminator for derived types. Required. Default value is None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """The discriminator for derived types. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DataSourceCredentials(_Model): + """Represents credentials that can be used to connect to a datasource. + + :ivar connection_string: The connection string for the datasource. Set to ```` (with + brackets) if you don't want the connection string updated. Set to ```` if you want to + remove the connection string value from the datasource. + :vartype connection_string: str + """ + + connection_string: Optional[str] = rest_field( + name="connectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """The connection string for the datasource. Set to ```` (with brackets) if you don't + want the connection string updated. Set to ```` if you want to remove the connection + string value from the datasource.""" + + @overload + def __init__( + self, + *, + connection_string: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DefaultCognitiveServicesAccount( + CognitiveServicesAccount, discriminator="#Microsoft.Azure.Search.DefaultCognitiveServices" +): + """An empty object that represents the default Azure AI service resource for a skillset. + + :ivar description: Description of the Azure AI service resource attached to a skillset. + :vartype description: str + :ivar odata_type: A URI fragment specifying the type of Azure AI service resource attached to a + skillset. Required. Default value is "#Microsoft.Azure.Search.DefaultCognitiveServices". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.DefaultCognitiveServices"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of Azure AI service resource attached to a skillset. + Required. Default value is \"#Microsoft.Azure.Search.DefaultCognitiveServices\".""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DefaultCognitiveServices" # type: ignore + + +class DictionaryDecompounderTokenFilter( + TokenFilter, discriminator="#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter" +): + """Decomposes compound words found in many Germanic languages. This token filter is implemented + using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar word_list: The list of words to match against. Required. + :vartype word_list: list[str] + :ivar min_word_size: The minimum word size. Only words longer than this get processed. Default + is 5. Maximum is 300. + :vartype min_word_size: int + :ivar min_subword_size: The minimum subword size. Only subwords longer than this are outputted. + Default is 2. Maximum is 300. + :vartype min_subword_size: int + :ivar max_subword_size: The maximum subword size. Only subwords shorter than this are + outputted. Default is 15. Maximum is 300. + :vartype max_subword_size: int + :ivar only_longest_match: A value indicating whether to add only the longest matching subword + to the output. Default is false. + :vartype only_longest_match: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter". + :vartype odata_type: str + """ + + word_list: list[str] = rest_field(name="wordList", visibility=["read", "create", "update", "delete", "query"]) + """The list of words to match against. Required.""" + min_word_size: Optional[int] = rest_field( + name="minWordSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The minimum word size. Only words longer than this get processed. Default is 5. Maximum is 300.""" + min_subword_size: Optional[int] = rest_field( + name="minSubwordSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The minimum subword size. Only subwords longer than this are outputted. Default is 2. Maximum + is 300.""" + max_subword_size: Optional[int] = rest_field( + name="maxSubwordSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum subword size. Only subwords shorter than this are outputted. Default is 15. Maximum + is 300.""" + only_longest_match: Optional[bool] = rest_field( + name="onlyLongestMatch", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to add only the longest matching subword to the output. Default is + false.""" + odata_type: Literal["#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + word_list: list[str], + min_word_size: Optional[int] = None, + min_subword_size: Optional[int] = None, + max_subword_size: Optional[int] = None, + only_longest_match: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter" # type: ignore + + +class ScoringFunction(_Model): + """Base type for functions that can modify document scores during ranking. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + DistanceScoringFunction, FreshnessScoringFunction, MagnitudeScoringFunction, TagScoringFunction + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar type: Type of ScoringFunction. Required. Default value is None. + :vartype type: str + """ + + __mapping__: dict[str, _Model] = {} + field_name: str = rest_field(name="fieldName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the field used as input to the scoring function. Required.""" + boost: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A multiplier for the raw score. Must be a positive number not equal to 1.0. Required.""" + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how boosting will be interpolated across document scores; defaults to + \"Linear\". Known values are: \"linear\", \"constant\", \"quadratic\", and \"logarithmic\".""" + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """Type of ScoringFunction. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + type: str, + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DistanceScoringFunction(ScoringFunction, discriminator="distance"): + """Defines a function that boosts scores based on distance from a geographic location. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the distance scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.DistanceScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is "distance". + :vartype type: str + """ + + parameters: "_models.DistanceScoringParameters" = rest_field( + name="distance", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the distance scoring function. Required.""" + type: Literal["distance"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"distance\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.DistanceScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "distance" # type: ignore + + +class DistanceScoringParameters(_Model): + """Provides parameter values to a distance scoring function. + + :ivar reference_point_parameter: The name of the parameter passed in search queries to specify + the reference location. Required. + :vartype reference_point_parameter: str + :ivar boosting_distance: The distance in kilometers from the reference location where the + boosting range ends. Required. + :vartype boosting_distance: float + """ + + reference_point_parameter: str = rest_field( + name="referencePointParameter", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the parameter passed in search queries to specify the reference location. Required.""" + boosting_distance: float = rest_field( + name="boostingDistance", visibility=["read", "create", "update", "delete", "query"] + ) + """The distance in kilometers from the reference location where the boosting range ends. Required.""" + + @overload + def __init__( + self, + *, + reference_point_parameter: str, + boosting_distance: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DocumentExtractionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.DocumentExtractionSkill"): + """A skill that extracts content from a file within the enrichment pipeline. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar parsing_mode: The parsingMode for the skill. Will be set to 'default' if not defined. + :vartype parsing_mode: str + :ivar data_to_extract: The type of data to be extracted for the skill. Will be set to + 'contentAndMetadata' if not defined. + :vartype data_to_extract: str + :ivar configuration: A dictionary of configurations for the skill. + :vartype configuration: dict[str, any] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.DocumentExtractionSkill". + :vartype odata_type: str + """ + + parsing_mode: Optional[str] = rest_field( + name="parsingMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The parsingMode for the skill. Will be set to 'default' if not defined.""" + data_to_extract: Optional[str] = rest_field( + name="dataToExtract", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of data to be extracted for the skill. Will be set to 'contentAndMetadata' if not + defined.""" + configuration: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A dictionary of configurations for the skill.""" + odata_type: Literal["#Microsoft.Skills.Util.DocumentExtractionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.DocumentExtractionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + parsing_mode: Optional[str] = None, + data_to_extract: Optional[str] = None, + configuration: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.DocumentExtractionSkill" # type: ignore + + +class DocumentIntelligenceLayoutSkill( + SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill" +): + """A skill that extracts content and layout information, via Azure AI Services, from files within + the enrichment pipeline. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar output_format: Controls the cardinality of the output produced by the skill. Default is + 'oneToMany'. Known values are: "text" and "markdown". + :vartype output_format: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat + :ivar output_mode: Controls the cardinality of the output produced by the skill. Default is + 'oneToMany'. "oneToMany" + :vartype output_mode: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode + :ivar markdown_header_depth: The depth of headers in the markdown output. Default is h6. Known + values are: "h1", "h2", "h3", "h4", "h5", and "h6". + :vartype markdown_header_depth: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth + :ivar extraction_options: Controls the cardinality of the content extracted from the document + by the skill. + :vartype extraction_options: list[str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions] + :ivar chunking_properties: Controls the cardinality for chunking the content. + :vartype chunking_properties: + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill". + :vartype odata_type: str + """ + + output_format: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"]] = rest_field( + name="outputFormat", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality of the output produced by the skill. Default is 'oneToMany'. Known + values are: \"text\" and \"markdown\".""" + output_mode: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"]] = rest_field( + name="outputMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality of the output produced by the skill. Default is 'oneToMany'. + \"oneToMany\"""" + markdown_header_depth: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth"]] = ( + rest_field(name="markdownHeaderDepth", visibility=["read", "create", "update", "delete", "query"]) + ) + """The depth of headers in the markdown output. Default is h6. Known values are: \"h1\", \"h2\", + \"h3\", \"h4\", \"h5\", and \"h6\".""" + extraction_options: Optional[list[Union[str, "_models.DocumentIntelligenceLayoutSkillExtractionOptions"]]] = ( + rest_field(name="extractionOptions", visibility=["read", "create", "update", "delete", "query"]) + ) + """Controls the cardinality of the content extracted from the document by the skill.""" + chunking_properties: Optional["_models.DocumentIntelligenceLayoutSkillChunkingProperties"] = rest_field( + name="chunkingProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality for chunking the content.""" + odata_type: Literal["#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + output_format: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"]] = None, + output_mode: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"]] = None, + markdown_header_depth: Optional[ + Union[str, "_models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth"] + ] = None, + extraction_options: Optional[ + list[Union[str, "_models.DocumentIntelligenceLayoutSkillExtractionOptions"]] + ] = None, + chunking_properties: Optional["_models.DocumentIntelligenceLayoutSkillChunkingProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill" # type: ignore + + +class DocumentIntelligenceLayoutSkillChunkingProperties(_Model): # pylint: disable=name-too-long + """Controls the cardinality for chunking the content. + + :ivar unit: The unit of the chunk. "characters" + :vartype unit: str or + ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit + :ivar maximum_length: The maximum chunk length in characters. Default is 500. + :vartype maximum_length: int + :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. + :vartype overlap_length: int + """ + + unit: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillChunkingUnit"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The unit of the chunk. \"characters\"""" + maximum_length: Optional[int] = rest_field( + name="maximumLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum chunk length in characters. Default is 500.""" + overlap_length: Optional[int] = rest_field( + name="overlapLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The length of overlap provided between two text chunks. Default is 0.""" + + @overload + def __init__( + self, + *, + unit: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillChunkingUnit"]] = None, + maximum_length: Optional[int] = None, + overlap_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DocumentKeysOrIds(_Model): + """The type of the keysOrIds. + + :ivar document_keys: document keys to be reset. + :vartype document_keys: list[str] + :ivar datasource_document_ids: datasource document identifiers to be reset. + :vartype datasource_document_ids: list[str] + """ + + document_keys: Optional[list[str]] = rest_field( + name="documentKeys", visibility=["read", "create", "update", "delete", "query"] + ) + """document keys to be reset.""" + datasource_document_ids: Optional[list[str]] = rest_field( + name="datasourceDocumentIds", visibility=["read", "create", "update", "delete", "query"] + ) + """datasource document identifiers to be reset.""" + + @overload + def __init__( + self, + *, + document_keys: Optional[list[str]] = None, + datasource_document_ids: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EdgeNGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.EdgeNGramTokenFilterV2"): + """Generates n-grams of the given size(s) starting from the front or the back of an input token. + This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar side: Specifies which side of the input the n-gram should be generated from. Default is + "front". Known values are: "front" and "back". + :vartype side: str or ~azure.search.documents.indexes.models.EdgeNGramTokenFilterSide + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies which side of the input the n-gram should be generated from. Default is \"front\". + Known values are: \"front\" and \"back\".""" + odata_type: Literal["#Microsoft.Azure.Search.EdgeNGramTokenFilterV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.EdgeNGramTokenFilterV2\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + side: Optional[Union[str, "_models.EdgeNGramTokenFilterSide"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2" # type: ignore + + +class EdgeNGramTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.EdgeNGramTokenizer"): + """Tokenizes the input from an edge into n-grams of the given size(s). This tokenizer is + implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar token_chars: Character classes to keep in the tokens. + :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.EdgeNGramTokenizer". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = rest_field( + name="tokenChars", visibility=["read", "create", "update", "delete", "query"] + ) + """Character classes to keep in the tokens.""" + odata_type: Literal["#Microsoft.Azure.Search.EdgeNGramTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.EdgeNGramTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.EdgeNGramTokenizer" # type: ignore + + +class ElisionTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.ElisionTokenFilter"): + """Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). This + token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar articles: The set of articles to remove. + :vartype articles: list[str] + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.ElisionTokenFilter". + :vartype odata_type: str + """ + + articles: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The set of articles to remove.""" + odata_type: Literal["#Microsoft.Azure.Search.ElisionTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.ElisionTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + articles: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ElisionTokenFilter" # type: ignore + + +class EntityLinkingSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.V3.EntityLinkingSkill"): + """Using the Text Analytics API, extracts linked entities from text. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.V3.EntityLinkingSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.V3.EntityLinkingSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.V3.EntityLinkingSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[str] = None, + minimum_precision: Optional[float] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.V3.EntityLinkingSkill" # type: ignore + + +class EntityRecognitionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.EntityRecognitionSkill"): + """This skill is deprecated. Use the V3.EntityRecognitionSkill instead. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar categories: A list of entity categories that should be extracted. + :vartype categories: list[str or ~azure.search.documents.indexes.models.EntityCategory] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", "el", + "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", and "tr". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage + :ivar include_typeless_entities: Determines whether or not to include entities which are well + known but don't conform to a pre-defined type. If this configuration is not set (default), set + to null or set to false, entities which don't conform to one of the pre-defined types will not + be surfaced. + :vartype include_typeless_entities: bool + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.EntityRecognitionSkill". + :vartype odata_type: str + """ + + categories: Optional[list[Union[str, "_models.EntityCategory"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of entity categories that should be extracted.""" + default_language_code: Optional[Union[str, "_models.EntityRecognitionSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"ar\", + \"cs\", \"zh-Hans\", \"zh-Hant\", \"da\", \"nl\", \"en\", \"fi\", \"fr\", \"de\", \"el\", + \"hu\", \"it\", \"ja\", \"ko\", \"no\", \"pl\", \"pt-PT\", \"pt-BR\", \"ru\", \"es\", \"sv\", + and \"tr\".""" + include_typeless_entities: Optional[bool] = rest_field( + name="includeTypelessEntities", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether or not to include entities which are well known but don't conform to a + pre-defined type. If this configuration is not set (default), set to null or set to false, + entities which don't conform to one of the pre-defined types will not be surfaced.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + odata_type: Literal["#Microsoft.Skills.Text.EntityRecognitionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.EntityRecognitionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + categories: Optional[list[Union[str, "_models.EntityCategory"]]] = None, + default_language_code: Optional[Union[str, "_models.EntityRecognitionSkillLanguage"]] = None, + include_typeless_entities: Optional[bool] = None, + minimum_precision: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.EntityRecognitionSkill" # type: ignore + + +class EntityRecognitionSkillV3(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.V3.EntityRecognitionSkill"): + """Using the Text Analytics API, extracts entities of different types from text. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar categories: A list of entity categories that should be extracted. + :vartype categories: list[str] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar model_version: The version of the model to use when calling the Text Analytics API. It + will default to the latest available when not specified. We recommend you do not specify this + value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.V3.EntityRecognitionSkill". + :vartype odata_type: str + """ + + categories: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of entity categories that should be extracted.""" + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics API. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.V3.EntityRecognitionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.V3.EntityRecognitionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + categories: Optional[list[str]] = None, + default_language_code: Optional[str] = None, + minimum_precision: Optional[float] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill" # type: ignore + + +class VectorSearchAlgorithmConfiguration(_Model): + """Contains configuration options specific to the algorithm used during indexing or querying. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ExhaustiveKnnAlgorithmConfiguration, HnswAlgorithmConfiguration + + :ivar name: The name to associate with this particular configuration. Required. + :vartype name: str + :ivar kind: Type of VectorSearchAlgorithmConfiguration. Required. Known values are: "hnsw" and + "exhaustiveKnn". + :vartype kind: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmKind + """ + + __mapping__: dict[str, _Model] = {} + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular configuration. Required.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of VectorSearchAlgorithmConfiguration. Required. Known values are: \"hnsw\" and + \"exhaustiveKnn\".""" + + @overload + def __init__( + self, + *, + name: str, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ExhaustiveKnnAlgorithmConfiguration(VectorSearchAlgorithmConfiguration, discriminator="exhaustiveKnn"): + """Contains configuration options specific to the exhaustive KNN algorithm used during querying, + which will perform brute-force search across the entire vector index. + + :ivar name: The name to associate with this particular configuration. Required. + :vartype name: str + :ivar parameters: Contains the parameters specific to exhaustive KNN algorithm. + :vartype parameters: ~azure.search.documents.indexes.models.ExhaustiveKnnParameters + :ivar kind: The name of the kind of algorithm being configured for use with vector search. + Required. Exhaustive KNN algorithm which will perform brute-force search. + :vartype kind: str or ~azure.search.documents.indexes.models.EXHAUSTIVE_KNN + """ + + parameters: Optional["_models.ExhaustiveKnnParameters"] = rest_field( + name="exhaustiveKnnParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to exhaustive KNN algorithm.""" + kind: Literal[VectorSearchAlgorithmKind.EXHAUSTIVE_KNN] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of algorithm being configured for use with vector search. Required. + Exhaustive KNN algorithm which will perform brute-force search.""" + + @overload + def __init__( + self, + *, + name: str, + parameters: Optional["_models.ExhaustiveKnnParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchAlgorithmKind.EXHAUSTIVE_KNN # type: ignore + + +class ExhaustiveKnnParameters(_Model): + """Contains the parameters specific to exhaustive KNN algorithm. + + :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", + "euclidean", "dotProduct", and "hamming". + :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric + """ + + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The similarity metric to use for vector comparisons. Known values are: \"cosine\", + \"euclidean\", \"dotProduct\", and \"hamming\".""" + + @overload + def __init__( + self, + *, + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FieldMapping(_Model): + """Defines a mapping between a field in a data source and a target field in an index. + + :ivar source_field_name: The name of the field in the data source. Required. + :vartype source_field_name: str + :ivar target_field_name: The name of the target field in the index. Same as the source field + name by default. + :vartype target_field_name: str + :ivar mapping_function: A function to apply to each source field value before indexing. + :vartype mapping_function: ~azure.search.documents.indexes.models.FieldMappingFunction + """ + + source_field_name: str = rest_field( + name="sourceFieldName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the field in the data source. Required.""" + target_field_name: Optional[str] = rest_field( + name="targetFieldName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the target field in the index. Same as the source field name by default.""" + mapping_function: Optional["_models.FieldMappingFunction"] = rest_field( + name="mappingFunction", visibility=["read", "create", "update", "delete", "query"] + ) + """A function to apply to each source field value before indexing.""" + + @overload + def __init__( + self, + *, + source_field_name: str, + target_field_name: Optional[str] = None, + mapping_function: Optional["_models.FieldMappingFunction"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FieldMappingFunction(_Model): + """Represents a function that transforms a value from a data source before indexing. + + :ivar name: The name of the field mapping function. Required. + :vartype name: str + :ivar parameters: A dictionary of parameter name/value pairs to pass to the function. Each + value must be of a primitive type. + :vartype parameters: dict[str, any] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the field mapping function. Required.""" + parameters: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A dictionary of parameter name/value pairs to pass to the function. Each value must be of a + primitive type.""" + + @overload + def __init__( + self, + *, + name: str, + parameters: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FreshnessScoringFunction(ScoringFunction, discriminator="freshness"): + """Defines a function that boosts scores based on the value of a date-time field. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the freshness scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.FreshnessScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is + "freshness". + :vartype type: str + """ + + parameters: "_models.FreshnessScoringParameters" = rest_field( + name="freshness", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the freshness scoring function. Required.""" + type: Literal["freshness"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"freshness\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.FreshnessScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "freshness" # type: ignore + + +class FreshnessScoringParameters(_Model): + """Provides parameter values to a freshness scoring function. + + :ivar boosting_duration: The expiration period after which boosting will stop for a particular + document. Required. + :vartype boosting_duration: ~datetime.timedelta + """ + + boosting_duration: datetime.timedelta = rest_field( + name="boostingDuration", visibility=["read", "create", "update", "delete", "query"] + ) + """The expiration period after which boosting will stop for a particular document. Required.""" + + @overload + def __init__( + self, + *, + boosting_duration: datetime.timedelta, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GetIndexStatisticsResult(_Model): + """Statistics for a given index. Statistics are collected periodically and are not guaranteed to + always be up-to-date. + + :ivar document_count: The number of documents in the index. Required. + :vartype document_count: int + :ivar storage_size: The amount of storage in bytes consumed by the index. Required. + :vartype storage_size: int + :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. + Required. + :vartype vector_index_size: int + """ + + document_count: int = rest_field(name="documentCount", visibility=["read", "create", "update", "delete", "query"]) + """The number of documents in the index. Required.""" + storage_size: int = rest_field(name="storageSize", visibility=["read", "create", "update", "delete", "query"]) + """The amount of storage in bytes consumed by the index. Required.""" + vector_index_size: int = rest_field( + name="vectorIndexSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The amount of memory in bytes consumed by vectors in the index. Required.""" + + @overload + def __init__( + self, + *, + document_count: int, + storage_size: int, + vector_index_size: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class HighWaterMarkChangeDetectionPolicy( + DataChangeDetectionPolicy, discriminator="#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" +): + """Defines a data change detection policy that captures changes based on the value of a high water + mark column. + + :ivar high_water_mark_column_name: The name of the high water mark column. Required. + :vartype high_water_mark_column_name: str + :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. + Default value is "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy". + :vartype odata_type: str + """ + + high_water_mark_column_name: str = rest_field( + name="highWaterMarkColumnName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the high water mark column. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data change detection policy. Required. Default value is + \"#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy\".""" + + @overload + def __init__( + self, + *, + high_water_mark_column_name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" # type: ignore + + +class HnswAlgorithmConfiguration(VectorSearchAlgorithmConfiguration, discriminator="hnsw"): + """Contains configuration options specific to the HNSW approximate nearest neighbors algorithm + used during indexing and querying. The HNSW algorithm offers a tunable trade-off between search + speed and accuracy. + + :ivar name: The name to associate with this particular configuration. Required. + :vartype name: str + :ivar parameters: Contains the parameters specific to HNSW algorithm. + :vartype parameters: ~azure.search.documents.indexes.models.HnswParameters + :ivar kind: The name of the kind of algorithm being configured for use with vector search. + Required. HNSW (Hierarchical Navigable Small World), a type of approximate nearest neighbors + algorithm. + :vartype kind: str or ~azure.search.documents.indexes.models.HNSW + """ + + parameters: Optional["_models.HnswParameters"] = rest_field( + name="hnswParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to HNSW algorithm.""" + kind: Literal[VectorSearchAlgorithmKind.HNSW] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of algorithm being configured for use with vector search. Required. HNSW + (Hierarchical Navigable Small World), a type of approximate nearest neighbors algorithm.""" + + @overload + def __init__( + self, + *, + name: str, + parameters: Optional["_models.HnswParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchAlgorithmKind.HNSW # type: ignore + + +class HnswParameters(_Model): + """Contains the parameters specific to the HNSW algorithm. + + :ivar m: The number of bi-directional links created for every new element during construction. + Increasing this parameter value may improve recall and reduce retrieval times for datasets with + high intrinsic dimensionality at the expense of increased memory consumption and longer + indexing time. + :vartype m: int + :ivar ef_construction: The size of the dynamic list containing the nearest neighbors, which is + used during index time. Increasing this parameter may improve index quality, at the expense of + increased indexing time. At a certain point, increasing this parameter leads to diminishing + returns. + :vartype ef_construction: int + :ivar ef_search: The size of the dynamic list containing the nearest neighbors, which is used + during search time. Increasing this parameter may improve search results, at the expense of + slower search. At a certain point, increasing this parameter leads to diminishing returns. + :vartype ef_search: int + :ivar metric: The similarity metric to use for vector comparisons. Known values are: "cosine", + "euclidean", "dotProduct", and "hamming". + :vartype metric: str or ~azure.search.documents.indexes.models.VectorSearchAlgorithmMetric + """ + + m: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of bi-directional links created for every new element during construction. + Increasing this parameter value may improve recall and reduce retrieval times for datasets with + high intrinsic dimensionality at the expense of increased memory consumption and longer + indexing time.""" + ef_construction: Optional[int] = rest_field( + name="efConstruction", visibility=["read", "create", "update", "delete", "query"] + ) + """The size of the dynamic list containing the nearest neighbors, which is used during index time. + Increasing this parameter may improve index quality, at the expense of increased indexing time. + At a certain point, increasing this parameter leads to diminishing returns.""" + ef_search: Optional[int] = rest_field(name="efSearch", visibility=["read", "create", "update", "delete", "query"]) + """The size of the dynamic list containing the nearest neighbors, which is used during search + time. Increasing this parameter may improve search results, at the expense of slower search. At + a certain point, increasing this parameter leads to diminishing returns.""" + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The similarity metric to use for vector comparisons. Known values are: \"cosine\", + \"euclidean\", \"dotProduct\", and \"hamming\".""" + + @overload + def __init__( + self, + *, + m: Optional[int] = None, + ef_construction: Optional[int] = None, + ef_search: Optional[int] = None, + metric: Optional[Union[str, "_models.VectorSearchAlgorithmMetric"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ImageAnalysisSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Vision.ImageAnalysisSkill"): + """A skill that analyzes image files. It extracts a rich set of visual features based on the image + content. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "ar", "az", "bg", "bs", "ca", "cs", "cy", "da", "de", "el", "en", "es", "et", + "eu", "fi", "fr", "ga", "gl", "he", "hi", "hr", "hu", "id", "it", "ja", "kk", "ko", "lt", "lv", + "mk", "ms", "nb", "nl", "pl", "prs", "pt-BR", "pt", "pt-PT", "ro", "ru", "sk", "sl", "sr-Cyrl", + "sr-Latn", "sv", "th", "tr", "uk", "vi", "zh", "zh-Hans", and "zh-Hant". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.ImageAnalysisSkillLanguage + :ivar visual_features: A list of visual features. + :vartype visual_features: list[str or ~azure.search.documents.indexes.models.VisualFeature] + :ivar details: A string indicating which domain-specific details to return. + :vartype details: list[str or ~azure.search.documents.indexes.models.ImageDetail] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Vision.ImageAnalysisSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.ImageAnalysisSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"ar\", + \"az\", \"bg\", \"bs\", \"ca\", \"cs\", \"cy\", \"da\", \"de\", \"el\", \"en\", \"es\", \"et\", + \"eu\", \"fi\", \"fr\", \"ga\", \"gl\", \"he\", \"hi\", \"hr\", \"hu\", \"id\", \"it\", \"ja\", + \"kk\", \"ko\", \"lt\", \"lv\", \"mk\", \"ms\", \"nb\", \"nl\", \"pl\", \"prs\", \"pt-BR\", + \"pt\", \"pt-PT\", \"ro\", \"ru\", \"sk\", \"sl\", \"sr-Cyrl\", \"sr-Latn\", \"sv\", \"th\", + \"tr\", \"uk\", \"vi\", \"zh\", \"zh-Hans\", and \"zh-Hant\".""" + visual_features: Optional[list[Union[str, "_models.VisualFeature"]]] = rest_field( + name="visualFeatures", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of visual features.""" + details: Optional[list[Union[str, "_models.ImageDetail"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A string indicating which domain-specific details to return.""" + odata_type: Literal["#Microsoft.Skills.Vision.ImageAnalysisSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Vision.ImageAnalysisSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.ImageAnalysisSkillLanguage"]] = None, + visual_features: Optional[list[Union[str, "_models.VisualFeature"]]] = None, + details: Optional[list[Union[str, "_models.ImageDetail"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Vision.ImageAnalysisSkill" # type: ignore + + +class IndexerCurrentState(_Model): + """Represents all of the state that defines and dictates the indexer's current execution. + + :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", + "indexingResetDocs", and "indexingResync". + :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode + :ivar all_docs_initial_tracking_state: Change tracking state used when indexing starts on all + documents in the datasource. + :vartype all_docs_initial_tracking_state: str + :ivar all_docs_final_tracking_state: Change tracking state value when indexing finishes on all + documents in the datasource. + :vartype all_docs_final_tracking_state: str + :ivar reset_docs_initial_tracking_state: Change tracking state used when indexing starts on + select, reset documents in the datasource. + :vartype reset_docs_initial_tracking_state: str + :ivar reset_docs_final_tracking_state: Change tracking state value when indexing finishes on + select, reset documents in the datasource. + :vartype reset_docs_final_tracking_state: str + :ivar resync_initial_tracking_state: Change tracking state used when indexing starts on + selective options from the datasource. + :vartype resync_initial_tracking_state: str + :ivar resync_final_tracking_state: Change tracking state value when indexing finishes on + selective options from the datasource. + :vartype resync_final_tracking_state: str + :ivar reset_document_keys: The list of document keys that have been reset. The document key is + the document's unique identifier for the data in the search index. The indexer will prioritize + selectively re-ingesting these keys. + :vartype reset_document_keys: list[str] + :ivar reset_datasource_document_ids: The list of datasource document ids that have been reset. + The datasource document id is the unique identifier for the data in the datasource. The indexer + will prioritize selectively re-ingesting these ids. + :vartype reset_datasource_document_ids: list[str] + """ + + mode: Optional[Union[str, "_models.IndexingMode"]] = rest_field(visibility=["read"]) + """The mode the indexer is running in. Known values are: \"indexingAllDocs\", + \"indexingResetDocs\", and \"indexingResync\".""" + all_docs_initial_tracking_state: Optional[str] = rest_field(name="allDocsInitialTrackingState", visibility=["read"]) + """Change tracking state used when indexing starts on all documents in the datasource.""" + all_docs_final_tracking_state: Optional[str] = rest_field(name="allDocsFinalTrackingState", visibility=["read"]) + """Change tracking state value when indexing finishes on all documents in the datasource.""" + reset_docs_initial_tracking_state: Optional[str] = rest_field( + name="resetDocsInitialTrackingState", visibility=["read"] + ) + """Change tracking state used when indexing starts on select, reset documents in the datasource.""" + reset_docs_final_tracking_state: Optional[str] = rest_field(name="resetDocsFinalTrackingState", visibility=["read"]) + """Change tracking state value when indexing finishes on select, reset documents in the + datasource.""" + resync_initial_tracking_state: Optional[str] = rest_field(name="resyncInitialTrackingState", visibility=["read"]) + """Change tracking state used when indexing starts on selective options from the datasource.""" + resync_final_tracking_state: Optional[str] = rest_field(name="resyncFinalTrackingState", visibility=["read"]) + """Change tracking state value when indexing finishes on selective options from the datasource.""" + reset_document_keys: Optional[list[str]] = rest_field(name="resetDocumentKeys", visibility=["read"]) + """The list of document keys that have been reset. The document key is the document's unique + identifier for the data in the search index. The indexer will prioritize selectively + re-ingesting these keys.""" + reset_datasource_document_ids: Optional[list[str]] = rest_field( + name="resetDatasourceDocumentIds", visibility=["read"] + ) + """The list of datasource document ids that have been reset. The datasource document id is the + unique identifier for the data in the datasource. The indexer will prioritize selectively + re-ingesting these ids.""" + + +class IndexerExecutionResult(_Model): + """Represents the result of an individual indexer execution. + + :ivar status: The outcome of this indexer execution. Required. Known values are: + "transientFailure", "success", "inProgress", and "reset". + :vartype status: str or ~azure.search.documents.indexes.models.IndexerExecutionStatus + :ivar status_detail: The outcome of this indexer execution. Known values are: "resetDocs" and + "resync". + :vartype status_detail: str or + ~azure.search.documents.indexes.models.IndexerExecutionStatusDetail + :ivar mode: The mode the indexer is running in. Known values are: "indexingAllDocs", + "indexingResetDocs", and "indexingResync". + :vartype mode: str or ~azure.search.documents.indexes.models.IndexingMode + :ivar current_state: All of the state that defines and dictates the indexer's current + execution. + :vartype current_state: ~azure.search.documents.indexes.models.IndexerCurrentState + :ivar error_message: The error message indicating the top-level error, if any. + :vartype error_message: str + :ivar start_time: The start time of this indexer execution. + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time of this indexer execution, if the execution has already completed. + :vartype end_time: ~datetime.datetime + :ivar errors: The item-level indexing errors. Required. + :vartype errors: list[~azure.search.documents.indexes.models.SearchIndexerError] + :ivar warnings: The item-level indexing warnings. Required. + :vartype warnings: list[~azure.search.documents.indexes.models.SearchIndexerWarning] + :ivar item_count: The number of items that were processed during this indexer execution. This + includes both successfully processed items and items where indexing was attempted but failed. + Required. + :vartype item_count: int + :ivar failed_item_count: The number of items that failed to be indexed during this indexer + execution. Required. + :vartype failed_item_count: int + :ivar initial_tracking_state: Change tracking state with which an indexer execution started. + :vartype initial_tracking_state: str + :ivar final_tracking_state: Change tracking state with which an indexer execution finished. + :vartype final_tracking_state: str + """ + + status: Union[str, "_models.IndexerExecutionStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The outcome of this indexer execution. Required. Known values are: \"transientFailure\", + \"success\", \"inProgress\", and \"reset\".""" + status_detail: Optional[Union[str, "_models.IndexerExecutionStatusDetail"]] = rest_field( + name="statusDetail", visibility=["read"] + ) + """The outcome of this indexer execution. Known values are: \"resetDocs\" and \"resync\".""" + mode: Optional[Union[str, "_models.IndexingMode"]] = rest_field(visibility=["read"]) + """The mode the indexer is running in. Known values are: \"indexingAllDocs\", + \"indexingResetDocs\", and \"indexingResync\".""" + current_state: Optional["_models.IndexerCurrentState"] = rest_field(name="currentState", visibility=["read"]) + """All of the state that defines and dictates the indexer's current execution.""" + error_message: Optional[str] = rest_field( + name="errorMessage", visibility=["read", "create", "update", "delete", "query"] + ) + """The error message indicating the top-level error, if any.""" + start_time: Optional[datetime.datetime] = rest_field( + name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start time of this indexer execution.""" + end_time: Optional[datetime.datetime] = rest_field( + name="endTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end time of this indexer execution, if the execution has already completed.""" + errors: list["_models.SearchIndexerError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The item-level indexing errors. Required.""" + warnings: list["_models.SearchIndexerWarning"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The item-level indexing warnings. Required.""" + item_count: int = rest_field(name="itemsProcessed", visibility=["read", "create", "update", "delete", "query"]) + """The number of items that were processed during this indexer execution. This includes both + successfully processed items and items where indexing was attempted but failed. Required.""" + failed_item_count: int = rest_field(name="itemsFailed", visibility=["read", "create", "update", "delete", "query"]) + """The number of items that failed to be indexed during this indexer execution. Required.""" + initial_tracking_state: Optional[str] = rest_field( + name="initialTrackingState", visibility=["read", "create", "update", "delete", "query"] + ) + """Change tracking state with which an indexer execution started.""" + final_tracking_state: Optional[str] = rest_field( + name="finalTrackingState", visibility=["read", "create", "update", "delete", "query"] + ) + """Change tracking state with which an indexer execution finished.""" + + @overload + def __init__( + self, + *, + status: Union[str, "_models.IndexerExecutionStatus"], + errors: list["_models.SearchIndexerError"], + warnings: list["_models.SearchIndexerWarning"], + item_count: int, + failed_item_count: int, + error_message: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + initial_tracking_state: Optional[str] = None, + final_tracking_state: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexerResyncBody(_Model): + """Request body for resync indexer operation. + + :ivar options: Indexer to re-ingest pre-selected permissions data from data source to index. + :vartype options: list[str or ~azure.search.documents.indexes.models.IndexerResyncOption] + """ + + options: Optional[list[Union[str, "_models.IndexerResyncOption"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Indexer to re-ingest pre-selected permissions data from data source to index.""" + + @overload + def __init__( + self, + *, + options: Optional[list[Union[str, "_models.IndexerResyncOption"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingParameters(_Model): + """Represents parameters for indexer execution. + + :ivar batch_size: The number of items that are read from the data source and indexed as a + single batch in order to improve performance. The default depends on the data source type. + :vartype batch_size: int + :ivar max_failed_items: The maximum number of items that can fail indexing for indexer + execution to still be considered successful. -1 means no limit. Default is 0. + :vartype max_failed_items: int + :ivar max_failed_items_per_batch: The maximum number of items in a single batch that can fail + indexing for the batch to still be considered successful. -1 means no limit. Default is 0. + :vartype max_failed_items_per_batch: int + :ivar configuration: A dictionary of indexer-specific configuration properties. Each name is + the name of a specific property. Each value must be of a primitive type. + :vartype configuration: ~azure.search.documents.indexes.models.IndexingParametersConfiguration + """ + + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) + """The number of items that are read from the data source and indexed as a single batch in order + to improve performance. The default depends on the data source type.""" + max_failed_items: Optional[int] = rest_field( + name="maxFailedItems", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of items that can fail indexing for indexer execution to still be considered + successful. -1 means no limit. Default is 0.""" + max_failed_items_per_batch: Optional[int] = rest_field( + name="maxFailedItemsPerBatch", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of items in a single batch that can fail indexing for the batch to still be + considered successful. -1 means no limit. Default is 0.""" + configuration: Optional["_models.IndexingParametersConfiguration"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of indexer-specific configuration properties. Each name is the name of a specific + property. Each value must be of a primitive type.""" + + @overload + def __init__( + self, + *, + batch_size: Optional[int] = None, + max_failed_items: Optional[int] = None, + max_failed_items_per_batch: Optional[int] = None, + configuration: Optional["_models.IndexingParametersConfiguration"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingParametersConfiguration(_Model): + """A dictionary of indexer-specific configuration properties. Each name is the name of a specific + property. Each value must be of a primitive type. + + :ivar parsing_mode: Represents the parsing mode for indexing from an Azure blob data source. + Known values are: "default", "text", "delimitedText", "json", "jsonArray", "jsonLines", and + "markdown". + :vartype parsing_mode: str or ~azure.search.documents.indexes.models.BlobIndexerParsingMode + :ivar excluded_file_name_extensions: Comma-delimited list of filename extensions to ignore when + processing from Azure blob storage. For example, you could exclude ".png, .mp4" to skip over + those files during indexing. + :vartype excluded_file_name_extensions: str + :ivar indexed_file_name_extensions: Comma-delimited list of filename extensions to select when + processing from Azure blob storage. For example, you could focus indexing on specific + application files ".docx, .pptx, .msg" to specifically include those file types. + :vartype indexed_file_name_extensions: str + :ivar fail_on_unsupported_content_type: For Azure blobs, set to false if you want to continue + indexing when an unsupported content type is encountered, and you don't know all the content + types (file extensions) in advance. + :vartype fail_on_unsupported_content_type: bool + :ivar fail_on_unprocessable_document: For Azure blobs, set to false if you want to continue + indexing if a document fails indexing. + :vartype fail_on_unprocessable_document: bool + :ivar index_storage_metadata_only_for_oversized_documents: For Azure blobs, set this property + to true to still index storage metadata for blob content that is too large to process. + Oversized blobs are treated as errors by default. For limits on blob size, see + `https://learn.microsoft.com/azure/search/search-limits-quotas-capacity + `_. + :vartype index_storage_metadata_only_for_oversized_documents: bool + :ivar delimited_text_headers: For CSV blobs, specifies a comma-delimited list of column + headers, useful for mapping source fields to destination fields in an index. + :vartype delimited_text_headers: str + :ivar delimited_text_delimiter: For CSV blobs, specifies the end-of-line single-character + delimiter for CSV files where each line starts a new document (for example, "|"). + :vartype delimited_text_delimiter: str + :ivar first_line_contains_headers: For CSV blobs, indicates that the first (non-blank) line of + each blob contains headers. + :vartype first_line_contains_headers: bool + :ivar markdown_parsing_submode: Specifies the submode that will determine whether a markdown + file will be parsed into exactly one search document or multiple search documents. Default is + ``oneToMany``. Known values are: "oneToMany" and "oneToOne". + :vartype markdown_parsing_submode: str or + ~azure.search.documents.indexes.models.MarkdownParsingSubmode + :ivar markdown_header_depth: Specifies the max header depth that will be considered while + grouping markdown content. Default is ``h6``. Known values are: "h1", "h2", "h3", "h4", "h5", + and "h6". + :vartype markdown_header_depth: str or + ~azure.search.documents.indexes.models.MarkdownHeaderDepth + :ivar document_root: For JSON arrays, given a structured or semi-structured document, you can + specify a path to the array using this property. + :vartype document_root: str + :ivar data_to_extract: Specifies the data to extract from Azure blob storage and tells the + indexer which data to extract from image content when "imageAction" is set to a value other + than "none". This applies to embedded image content in a .PDF or other application, or image + files such as .jpg and .png, in Azure blobs. Known values are: "storageMetadata", + "allMetadata", and "contentAndMetadata". + :vartype data_to_extract: str or + ~azure.search.documents.indexes.models.BlobIndexerDataToExtract + :ivar image_action: Determines how to process embedded images and image files in Azure blob + storage. Setting the "imageAction" configuration to any value other than "none" requires that + a skillset also be attached to that indexer. Known values are: "none", + "generateNormalizedImages", and "generateNormalizedImagePerPage". + :vartype image_action: str or ~azure.search.documents.indexes.models.BlobIndexerImageAction + :ivar allow_skillset_to_read_file_data: If true, will create a path //document//file_data that + is an object representing the original file data downloaded from your blob data source. This + allows you to pass the original file data to a custom skill for processing within the + enrichment pipeline, or to the Document Extraction skill. + :vartype allow_skillset_to_read_file_data: bool + :ivar pdf_text_rotation_algorithm: Determines algorithm for text extraction from PDF files in + Azure blob storage. Known values are: "none" and "detectAngles". + :vartype pdf_text_rotation_algorithm: str or + ~azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm + :ivar execution_environment: Specifies the environment in which the indexer should execute. + Known values are: "standard" and "private". + :vartype execution_environment: str or + ~azure.search.documents.indexes.models.IndexerExecutionEnvironment + :ivar query_timeout: Increases the timeout beyond the 5-minute default for Azure SQL database + data sources, specified in the format "hh:mm:ss". + :vartype query_timeout: str + """ + + parsing_mode: Optional[Union[str, "_models.BlobIndexerParsingMode"]] = rest_field( + name="parsingMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Represents the parsing mode for indexing from an Azure blob data source. Known values are: + \"default\", \"text\", \"delimitedText\", \"json\", \"jsonArray\", \"jsonLines\", and + \"markdown\".""" + excluded_file_name_extensions: Optional[str] = rest_field( + name="excludedFileNameExtensions", visibility=["read", "create", "update", "delete", "query"] + ) + """Comma-delimited list of filename extensions to ignore when processing from Azure blob storage. + For example, you could exclude \".png, .mp4\" to skip over those files during indexing.""" + indexed_file_name_extensions: Optional[str] = rest_field( + name="indexedFileNameExtensions", visibility=["read", "create", "update", "delete", "query"] + ) + """Comma-delimited list of filename extensions to select when processing from Azure blob storage. + For example, you could focus indexing on specific application files \".docx, .pptx, .msg\" to + specifically include those file types.""" + fail_on_unsupported_content_type: Optional[bool] = rest_field( + name="failOnUnsupportedContentType", visibility=["read", "create", "update", "delete", "query"] + ) + """For Azure blobs, set to false if you want to continue indexing when an unsupported content type + is encountered, and you don't know all the content types (file extensions) in advance.""" + fail_on_unprocessable_document: Optional[bool] = rest_field( + name="failOnUnprocessableDocument", visibility=["read", "create", "update", "delete", "query"] + ) + """For Azure blobs, set to false if you want to continue indexing if a document fails indexing.""" + index_storage_metadata_only_for_oversized_documents: Optional[bool] = rest_field( + name="indexStorageMetadataOnlyForOversizedDocuments", visibility=["read", "create", "update", "delete", "query"] + ) + """For Azure blobs, set this property to true to still index storage metadata for blob content + that is too large to process. Oversized blobs are treated as errors by default. For limits on + blob size, see `https://learn.microsoft.com/azure/search/search-limits-quotas-capacity + `_.""" + delimited_text_headers: Optional[str] = rest_field( + name="delimitedTextHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """For CSV blobs, specifies a comma-delimited list of column headers, useful for mapping source + fields to destination fields in an index.""" + delimited_text_delimiter: Optional[str] = rest_field( + name="delimitedTextDelimiter", visibility=["read", "create", "update", "delete", "query"] + ) + """For CSV blobs, specifies the end-of-line single-character delimiter for CSV files where each + line starts a new document (for example, \"|\").""" + first_line_contains_headers: Optional[bool] = rest_field( + name="firstLineContainsHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """For CSV blobs, indicates that the first (non-blank) line of each blob contains headers.""" + markdown_parsing_submode: Optional[Union[str, "_models.MarkdownParsingSubmode"]] = rest_field( + name="markdownParsingSubmode", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the submode that will determine whether a markdown file will be parsed into exactly + one search document or multiple search documents. Default is ``oneToMany``. Known values are: + \"oneToMany\" and \"oneToOne\".""" + markdown_header_depth: Optional[Union[str, "_models.MarkdownHeaderDepth"]] = rest_field( + name="markdownHeaderDepth", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the max header depth that will be considered while grouping markdown content. Default + is ``h6``. Known values are: \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", and \"h6\".""" + document_root: Optional[str] = rest_field( + name="documentRoot", visibility=["read", "create", "update", "delete", "query"] + ) + """For JSON arrays, given a structured or semi-structured document, you can specify a path to the + array using this property.""" + data_to_extract: Optional[Union[str, "_models.BlobIndexerDataToExtract"]] = rest_field( + name="dataToExtract", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the data to extract from Azure blob storage and tells the indexer which data to + extract from image content when \"imageAction\" is set to a value other than \"none\". This + applies to embedded image content in a .PDF or other application, or image files such as .jpg + and .png, in Azure blobs. Known values are: \"storageMetadata\", \"allMetadata\", and + \"contentAndMetadata\".""" + image_action: Optional[Union[str, "_models.BlobIndexerImageAction"]] = rest_field( + name="imageAction", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines how to process embedded images and image files in Azure blob storage. Setting the + \"imageAction\" configuration to any value other than \"none\" requires that a skillset also be + attached to that indexer. Known values are: \"none\", \"generateNormalizedImages\", and + \"generateNormalizedImagePerPage\".""" + allow_skillset_to_read_file_data: Optional[bool] = rest_field( + name="allowSkillsetToReadFileData", visibility=["read", "create", "update", "delete", "query"] + ) + """If true, will create a path //document//file_data that is an object representing the original + file data downloaded from your blob data source. This allows you to pass the original file data + to a custom skill for processing within the enrichment pipeline, or to the Document Extraction + skill.""" + pdf_text_rotation_algorithm: Optional[Union[str, "_models.BlobIndexerPDFTextRotationAlgorithm"]] = rest_field( + name="pdfTextRotationAlgorithm", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines algorithm for text extraction from PDF files in Azure blob storage. Known values + are: \"none\" and \"detectAngles\".""" + execution_environment: Optional[Union[str, "_models.IndexerExecutionEnvironment"]] = rest_field( + name="executionEnvironment", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the environment in which the indexer should execute. Known values are: \"standard\" + and \"private\".""" + query_timeout: Optional[str] = rest_field( + name="queryTimeout", visibility=["read", "create", "update", "delete", "query"] + ) + """Increases the timeout beyond the 5-minute default for Azure SQL database data sources, + specified in the format \"hh:mm:ss\".""" + + @overload + def __init__( + self, + *, + parsing_mode: Optional[Union[str, "_models.BlobIndexerParsingMode"]] = None, + excluded_file_name_extensions: Optional[str] = None, + indexed_file_name_extensions: Optional[str] = None, + fail_on_unsupported_content_type: Optional[bool] = None, + fail_on_unprocessable_document: Optional[bool] = None, + index_storage_metadata_only_for_oversized_documents: Optional[bool] = None, + delimited_text_headers: Optional[str] = None, + delimited_text_delimiter: Optional[str] = None, + first_line_contains_headers: Optional[bool] = None, + markdown_parsing_submode: Optional[Union[str, "_models.MarkdownParsingSubmode"]] = None, + markdown_header_depth: Optional[Union[str, "_models.MarkdownHeaderDepth"]] = None, + document_root: Optional[str] = None, + data_to_extract: Optional[Union[str, "_models.BlobIndexerDataToExtract"]] = None, + image_action: Optional[Union[str, "_models.BlobIndexerImageAction"]] = None, + allow_skillset_to_read_file_data: Optional[bool] = None, + pdf_text_rotation_algorithm: Optional[Union[str, "_models.BlobIndexerPDFTextRotationAlgorithm"]] = None, + execution_environment: Optional[Union[str, "_models.IndexerExecutionEnvironment"]] = None, + query_timeout: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingSchedule(_Model): + """Represents a schedule for indexer execution. + + :ivar interval: The interval of time between indexer executions. Required. + :vartype interval: ~datetime.timedelta + :ivar start_time: The time when an indexer should start running. + :vartype start_time: ~datetime.datetime + """ + + interval: datetime.timedelta = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The interval of time between indexer executions. Required.""" + start_time: Optional[datetime.datetime] = rest_field( + name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time when an indexer should start running.""" + + @overload + def __init__( + self, + *, + interval: datetime.timedelta, + start_time: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexStatisticsSummary(_Model): + """Statistics for a given index. Statistics are collected periodically and are not guaranteed to + always be up-to-date. + + :ivar name: The name of the index. Required. + :vartype name: str + :ivar document_count: The number of documents in the index. Required. + :vartype document_count: int + :ivar storage_size: The amount of storage in bytes consumed by the index. Required. + :vartype storage_size: int + :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. + :vartype vector_index_size: int + """ + + name: str = rest_field(visibility=["read"]) + """The name of the index. Required.""" + document_count: int = rest_field(name="documentCount", visibility=["read"]) + """The number of documents in the index. Required.""" + storage_size: int = rest_field(name="storageSize", visibility=["read"]) + """The amount of storage in bytes consumed by the index. Required.""" + vector_index_size: Optional[int] = rest_field(name="vectorIndexSize", visibility=["read"]) + """The amount of memory in bytes consumed by vectors in the index.""" + + +class InputFieldMappingEntry(_Model): + """Input field mapping for a skill. + + :ivar name: The name of the input. Required. + :vartype name: str + :ivar source: The source of the input. + :vartype source: str + :ivar source_context: The source context used for selecting recursive inputs. + :vartype source_context: str + :ivar inputs: The recursive inputs used when creating a complex type. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the input. Required.""" + source: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The source of the input.""" + source_context: Optional[str] = rest_field( + name="sourceContext", visibility=["read", "create", "update", "delete", "query"] + ) + """The source context used for selecting recursive inputs.""" + inputs: Optional[list["_models.InputFieldMappingEntry"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The recursive inputs used when creating a complex type.""" + + @overload + def __init__( + self, + *, + name: str, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KeepTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.KeepTokenFilter"): + """A token filter that only keeps tokens with text contained in a specified list of words. This + token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar keep_words: The list of words to keep. Required. + :vartype keep_words: list[str] + :ivar lower_case_keep_words: A value indicating whether to lower case all words first. Default + is false. + :vartype lower_case_keep_words: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.KeepTokenFilter". + :vartype odata_type: str + """ + + keep_words: list[str] = rest_field(name="keepWords", visibility=["read", "create", "update", "delete", "query"]) + """The list of words to keep. Required.""" + lower_case_keep_words: Optional[bool] = rest_field( + name="keepWordsCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to lower case all words first. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.KeepTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.KeepTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + keep_words: list[str], + lower_case_keep_words: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeepTokenFilter" # type: ignore + + +class KeyPhraseExtractionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.KeyPhraseExtractionSkill"): + """A skill that uses text analytics for key phrase extraction. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "da", "nl", "en", "fi", "fr", "de", "it", "ja", "ko", "no", "pl", "pt-PT", + "pt-BR", "ru", "es", and "sv". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage + :ivar max_key_phrase_count: A number indicating how many key phrases to return. If absent, all + identified key phrases will be returned. + :vartype max_key_phrase_count: int + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.KeyPhraseExtractionSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.KeyPhraseExtractionSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"da\", + \"nl\", \"en\", \"fi\", \"fr\", \"de\", \"it\", \"ja\", \"ko\", \"no\", \"pl\", \"pt-PT\", + \"pt-BR\", \"ru\", \"es\", and \"sv\".""" + max_key_phrase_count: Optional[int] = rest_field( + name="maxKeyPhraseCount", visibility=["read", "create", "update", "delete", "query"] + ) + """A number indicating how many key phrases to return. If absent, all identified key phrases will + be returned.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.KeyPhraseExtractionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.KeyPhraseExtractionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.KeyPhraseExtractionSkillLanguage"]] = None, + max_key_phrase_count: Optional[int] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.KeyPhraseExtractionSkill" # type: ignore + + +class KeywordMarkerTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.KeywordMarkerTokenFilter"): + """Marks terms as keywords. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar keywords: A list of words to mark as keywords. Required. + :vartype keywords: list[str] + :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted + to lower case first. Default is false. + :vartype ignore_case: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.KeywordMarkerTokenFilter". + :vartype odata_type: str + """ + + keywords: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of words to mark as keywords. Required.""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to ignore case. If true, all words are converted to lower case + first. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.KeywordMarkerTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.KeywordMarkerTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + keywords: list[str], + ignore_case: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeywordMarkerTokenFilter" # type: ignore + + +class KeywordTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.KeywordTokenizerV2"): + """Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 256. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.KeywordTokenizerV2". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 256. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.KeywordTokenizerV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.KeywordTokenizerV2\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.KeywordTokenizerV2" # type: ignore + + +class KnowledgeAgent(_Model): + """Represents a knowledge agent definition. + + :ivar name: The name of the knowledge agent. Required. + :vartype name: str + :ivar models: Contains configuration options on how to connect to AI models. Required. + :vartype models: list[~azure.search.documents.indexes.models.KnowledgeAgentModel] + :ivar knowledge_sources: Knowledge sources referenced by this agent. Required. + :vartype knowledge_sources: + list[~azure.search.documents.indexes.models.KnowledgeSourceReference] + :ivar output_configuration: Output configuration for the agent. + :vartype output_configuration: + ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfiguration + :ivar request_limits: Request limits for the agent. + :vartype request_limits: ~azure.search.documents.indexes.models.KnowledgeAgentRequestLimits + :ivar retrieval_instructions: Instructions considered by the knowledge agent when developing + query plan. + :vartype retrieval_instructions: str + :ivar e_tag: The ETag of the agent. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar description: The description of the agent. + :vartype description: str + """ + + name: str = rest_field(visibility=["read"]) + """The name of the knowledge agent. Required.""" + models: list["_models.KnowledgeAgentModel"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Contains configuration options on how to connect to AI models. Required.""" + knowledge_sources: list["_models.KnowledgeSourceReference"] = rest_field( + name="knowledgeSources", visibility=["read", "create", "update", "delete", "query"] + ) + """Knowledge sources referenced by this agent. Required.""" + output_configuration: Optional["_models.KnowledgeAgentOutputConfiguration"] = rest_field( + name="outputConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """Output configuration for the agent.""" + request_limits: Optional["_models.KnowledgeAgentRequestLimits"] = rest_field( + name="requestLimits", visibility=["read", "create", "update", "delete", "query"] + ) + """Request limits for the agent.""" + retrieval_instructions: Optional[str] = rest_field( + name="retrievalInstructions", visibility=["read", "create", "update", "delete", "query"] + ) + """Instructions considered by the knowledge agent when developing query plan.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the agent.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the agent.""" + + @overload + def __init__( + self, + *, + models: list["_models.KnowledgeAgentModel"], + knowledge_sources: list["_models.KnowledgeSourceReference"], + output_configuration: Optional["_models.KnowledgeAgentOutputConfiguration"] = None, + request_limits: Optional["_models.KnowledgeAgentRequestLimits"] = None, + retrieval_instructions: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeAgentModel(_Model): + """Specifies the connection parameters for the model to use for query planning. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeAgentAzureOpenAiModel + + :ivar kind: The AI model to be used for query planning. Required. "azureOpenAI" + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeAgentModelKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The AI model to be used for query planning. Required. \"azureOpenAI\"""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeAgentAzureOpenAiModel(KnowledgeAgentModel, discriminator="azureOpenAI"): + """Specifies the Azure OpenAI resource used to do query planning. + + :ivar kind: Required. Use Azure Open AI models for query planning. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_OPEN_AI + :ivar azure_open_ai_parameters: Azure OpenAI parameters. Required. + :vartype azure_open_ai_parameters: ~azure.search.documents.indexes.models.AzureOpenAiParameters + """ + + kind: Literal[KnowledgeAgentModelKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. Use Azure Open AI models for query planning.""" + azure_open_ai_parameters: "_models.AzureOpenAiParameters" = rest_field( + name="azureOpenAIParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Azure OpenAI parameters. Required.""" + + @overload + def __init__( + self, + *, + azure_open_ai_parameters: "_models.AzureOpenAiParameters", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeAgentModelKind.AZURE_OPEN_AI # type: ignore + + +class KnowledgeAgentOutputConfiguration(_Model): + """Output configuration for knowledge agent. + + :ivar modality: The output configuration for the agent. Known values are: "answerSynthesis" and + "extractiveData". + :vartype modality: str or + ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfigurationModality + :ivar answer_instructions: Instructions considered by the knowledge agent when generating + answers. + :vartype answer_instructions: str + :ivar attempt_fast_path: Indicates whether the agent should attempt to issue the most recent + chat message as a direct query to the knowledge sources, bypassing the model calls. + :vartype attempt_fast_path: bool + :ivar include_activity: Indicates retrieval results should include activity information. + :vartype include_activity: bool + """ + + modality: Optional[Union[str, "_models.KnowledgeAgentOutputConfigurationModality"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The output configuration for the agent. Known values are: \"answerSynthesis\" and + \"extractiveData\".""" + answer_instructions: Optional[str] = rest_field( + name="answerInstructions", visibility=["read", "create", "update", "delete", "query"] + ) + """Instructions considered by the knowledge agent when generating answers.""" + attempt_fast_path: Optional[bool] = rest_field( + name="attemptFastPath", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether the agent should attempt to issue the most recent chat message as a direct + query to the knowledge sources, bypassing the model calls.""" + include_activity: Optional[bool] = rest_field( + name="includeActivity", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates retrieval results should include activity information.""" + + @overload + def __init__( + self, + *, + modality: Optional[Union[str, "_models.KnowledgeAgentOutputConfigurationModality"]] = None, + answer_instructions: Optional[str] = None, + attempt_fast_path: Optional[bool] = None, + include_activity: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeAgentRequestLimits(_Model): + """Guardrails to limit how much resources are utilized for a single agent retrieval request. + + :ivar max_runtime_in_seconds: The maximum runtime in seconds. + :vartype max_runtime_in_seconds: int + :ivar max_output_size: Limits the maximum size of the content in the output. + :vartype max_output_size: int + """ + + max_runtime_in_seconds: Optional[int] = rest_field( + name="maxRuntimeInSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum runtime in seconds.""" + max_output_size: Optional[int] = rest_field( + name="maxOutputSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Limits the maximum size of the content in the output.""" + + @overload + def __init__( + self, + *, + max_runtime_in_seconds: Optional[int] = None, + max_output_size: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeSourceReference(_Model): + """Reference to a knowledge source. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar max_sub_queries: The maximum number of queries that can be issued at a time when + retrieving data from this source. + :vartype max_sub_queries: int + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the knowledge source. Required.""" + include_references: Optional[bool] = rest_field( + name="includeReferences", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether references should be included for data retrieved from this source.""" + include_reference_source_data: Optional[bool] = rest_field( + name="includeReferenceSourceData", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether references should include the structured data obtained during retrieval in + their payload.""" + always_query_source: Optional[bool] = rest_field( + name="alwaysQuerySource", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates that this knowledge source should bypass source selection and always be queried at + retrieval time.""" + max_sub_queries: Optional[int] = rest_field( + name="maxSubQueries", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of queries that can be issued at a time when retrieving data from this + source.""" + reranker_threshold: Optional[float] = rest_field( + name="rerankerThreshold", visibility=["read", "create", "update", "delete", "query"] + ) + """The reranker threshold all retrieved documents must meet to be included in the response.""" + + @overload + def __init__( + self, + *, + name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + max_sub_queries: Optional[int] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LanguageDetectionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.LanguageDetectionSkill"): + """A skill that detects the language of input text and reports a single language code for every + document submitted on the request. The language code is paired with a score indicating the + confidence of the analysis. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_country_hint: A country code to use as a hint to the language detection model if + it cannot disambiguate the language. + :vartype default_country_hint: str + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.LanguageDetectionSkill". + :vartype odata_type: str + """ + + default_country_hint: Optional[str] = rest_field( + name="defaultCountryHint", visibility=["read", "create", "update", "delete", "query"] + ) + """A country code to use as a hint to the language detection model if it cannot disambiguate the + language.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.LanguageDetectionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.LanguageDetectionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_country_hint: Optional[str] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.LanguageDetectionSkill" # type: ignore + + +class LengthTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.LengthTokenFilter"): + """Removes words that are too long or too short. This token filter is implemented using Apache + Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_length: The minimum length in characters. Default is 0. Maximum is 300. Must be less + than the value of max. + :vartype min_length: int + :ivar max_length: The maximum length in characters. Default and maximum is 300. + :vartype max_length: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.LengthTokenFilter". + :vartype odata_type: str + """ + + min_length: Optional[int] = rest_field(name="min", visibility=["read", "create", "update", "delete", "query"]) + """The minimum length in characters. Default is 0. Maximum is 300. Must be less than the value of + max.""" + max_length: Optional[int] = rest_field(name="max", visibility=["read", "create", "update", "delete", "query"]) + """The maximum length in characters. Default and maximum is 300.""" + odata_type: Literal["#Microsoft.Azure.Search.LengthTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.LengthTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.LengthTokenFilter" # type: ignore + + +class LimitTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.LimitTokenFilter"): + """Limits the number of tokens while indexing. This token filter is implemented using Apache + Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_count: The maximum number of tokens to produce. Default is 1. + :vartype max_token_count: int + :ivar consume_all_tokens: A value indicating whether all tokens from the input must be consumed + even if maxTokenCount is reached. Default is false. + :vartype consume_all_tokens: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.LimitTokenFilter". + :vartype odata_type: str + """ + + max_token_count: Optional[int] = rest_field( + name="maxTokenCount", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of tokens to produce. Default is 1.""" + consume_all_tokens: Optional[bool] = rest_field( + name="consumeAllTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether all tokens from the input must be consumed even if maxTokenCount is + reached. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.LimitTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.LimitTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_count: Optional[int] = None, + consume_all_tokens: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.LimitTokenFilter" # type: ignore + + +class ListDataSourcesResult(_Model): + """Response from a List Datasources request. If successful, it includes the full definitions of + all datasources. + + :ivar data_sources: The datasources in the Search service. Required. + :vartype data_sources: list[~azure.search.documents.indexes.models.SearchIndexerDataSource] + """ + + data_sources: list["_models.SearchIndexerDataSource"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The datasources in the Search service. Required.""" + + @overload + def __init__( + self, + *, + data_sources: list["_models.SearchIndexerDataSource"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListIndexersResult(_Model): + """Response from a List Indexers request. If successful, it includes the full definitions of all + indexers. + + :ivar indexers: The indexers in the Search service. Required. + :vartype indexers: list[~azure.search.documents.indexes.models.SearchIndexer] + """ + + indexers: list["_models.SearchIndexer"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The indexers in the Search service. Required.""" + + @overload + def __init__( + self, + *, + indexers: list["_models.SearchIndexer"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListKnowledgeAgentsResult(_Model): + """Result from listing knowledge agents. + + :ivar value: The knowledge agents in the service. Required. + :vartype value: list[~azure.search.documents.indexes.models.KnowledgeAgent] + """ + + value: list["_models.KnowledgeAgent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The knowledge agents in the service. Required.""" + + @overload + def __init__( + self, + *, + value: list["_models.KnowledgeAgent"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListKnowledgeSourcesResult(_Model): + """Result from listing knowledge sources. + + :ivar value: The knowledge sources in the service. Required. + :vartype value: list[~azure.search.documents.indexes.models.KnowledgeSource] + """ + + value: list["_models.KnowledgeSource"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The knowledge sources in the service. Required.""" + + @overload + def __init__( + self, + *, + value: list["_models.KnowledgeSource"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListSkillsetsResult(_Model): + """Response from a list skillset request. If successful, it includes the full definitions of all + skillsets. + + :ivar skillsets: The skillsets defined in the Search service. Required. + :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + """ + + skillsets: list["_models.SearchIndexerSkillset"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The skillsets defined in the Search service. Required.""" + + @overload + def __init__( + self, + *, + skillsets: list["_models.SearchIndexerSkillset"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListSynonymMapsResult(_Model): + """Response from a List SynonymMaps request. If successful, it includes the full definitions of + all synonym maps. + + :ivar synonym_maps: The synonym maps in the Search service. Required. + :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] + """ + + synonym_maps: list["_models.SynonymMap"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The synonym maps in the Search service. Required.""" + + @overload + def __init__( + self, + *, + synonym_maps: list["_models.SynonymMap"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LuceneStandardAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StandardAnalyzer"): + """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop + filter. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar stopwords: A list of stopwords. + :vartype stopwords: list[str] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.StandardAnalyzer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stopwords.""" + odata_type: Literal["#Microsoft.Azure.Search.StandardAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.StandardAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + stopwords: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StandardAnalyzer" # type: ignore + + +class LuceneStandardTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.StandardTokenizerV2"): + """Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using + Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.StandardTokenizerV2". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.StandardTokenizerV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.StandardTokenizerV2\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StandardTokenizerV2" # type: ignore + + +class MagnitudeScoringFunction(ScoringFunction, discriminator="magnitude"): + """Defines a function that boosts scores based on the magnitude of a numeric field. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the magnitude scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.MagnitudeScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is + "magnitude". + :vartype type: str + """ + + parameters: "_models.MagnitudeScoringParameters" = rest_field( + name="magnitude", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the magnitude scoring function. Required.""" + type: Literal["magnitude"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"magnitude\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.MagnitudeScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "magnitude" # type: ignore + + +class MagnitudeScoringParameters(_Model): + """Provides parameter values to a magnitude scoring function. + + :ivar boosting_range_start: The field value at which boosting starts. Required. + :vartype boosting_range_start: float + :ivar boosting_range_end: The field value at which boosting ends. Required. + :vartype boosting_range_end: float + :ivar should_boost_beyond_range_by_constant: A value indicating whether to apply a constant + boost for field values beyond the range end value; default is false. + :vartype should_boost_beyond_range_by_constant: bool + """ + + boosting_range_start: float = rest_field( + name="boostingRangeStart", visibility=["read", "create", "update", "delete", "query"] + ) + """The field value at which boosting starts. Required.""" + boosting_range_end: float = rest_field( + name="boostingRangeEnd", visibility=["read", "create", "update", "delete", "query"] + ) + """The field value at which boosting ends. Required.""" + should_boost_beyond_range_by_constant: Optional[bool] = rest_field( + name="constantBoostBeyondRange", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to apply a constant boost for field values beyond the range end + value; default is false.""" + + @overload + def __init__( + self, + *, + boosting_range_start: float, + boosting_range_end: float, + should_boost_beyond_range_by_constant: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MappingCharFilter(CharFilter, discriminator="#Microsoft.Azure.Search.MappingCharFilter"): + """A character filter that applies mappings defined with the mappings option. Matching is greedy + (longest pattern matching at a given point wins). Replacement is allowed to be the empty + string. This character filter is implemented using Apache Lucene. + + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar mappings: A list of mappings of the following format: "a=>b" (all occurrences of the + character "a" will be replaced with character "b"). Required. + :vartype mappings: list[str] + :ivar odata_type: A URI fragment specifying the type of char filter. Required. Default value is + "#Microsoft.Azure.Search.MappingCharFilter". + :vartype odata_type: str + """ + + mappings: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of mappings of the following format: \"a=>b\" (all occurrences of the character \"a\" + will be replaced with character \"b\"). Required.""" + odata_type: Literal["#Microsoft.Azure.Search.MappingCharFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of char filter. Required. Default value is + \"#Microsoft.Azure.Search.MappingCharFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + mappings: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.MappingCharFilter" # type: ignore + + +class MergeSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.MergeSkill"): + """A skill for merging two or more strings into a single unified string, with an optional + user-defined delimiter separating each component part. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar insert_pre_tag: The tag indicates the start of the merged text. By default, the tag is an + empty space. + :vartype insert_pre_tag: str + :ivar insert_post_tag: The tag indicates the end of the merged text. By default, the tag is an + empty space. + :vartype insert_post_tag: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.MergeSkill". + :vartype odata_type: str + """ + + insert_pre_tag: Optional[str] = rest_field( + name="insertPreTag", visibility=["read", "create", "update", "delete", "query"] + ) + """The tag indicates the start of the merged text. By default, the tag is an empty space.""" + insert_post_tag: Optional[str] = rest_field( + name="insertPostTag", visibility=["read", "create", "update", "delete", "query"] + ) + """The tag indicates the end of the merged text. By default, the tag is an empty space.""" + odata_type: Literal["#Microsoft.Skills.Text.MergeSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.MergeSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + insert_pre_tag: Optional[str] = None, + insert_post_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.MergeSkill" # type: ignore + + +class MicrosoftLanguageStemmingTokenizer( + LexicalTokenizer, discriminator="#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer" +): + """Divides text using language-specific rules and reduces words to their base forms. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are + split. Maximum token length that can be used is 300 characters. Tokens longer than 300 + characters are first split into tokens of length 300 and then each of those tokens is split + based on the max token length set. Default is 255. + :vartype max_token_length: int + :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as + the search tokenizer, set to false if used as the indexing tokenizer. Default is false. + :vartype is_search_tokenizer: bool + :ivar language: The language to use. The default is English. Known values are: "arabic", + "bangla", "bulgarian", "catalan", "croatian", "czech", "danish", "dutch", "english", + "estonian", "finnish", "french", "german", "greek", "gujarati", "hebrew", "hindi", "hungarian", + "icelandic", "indonesian", "italian", "kannada", "latvian", "lithuanian", "malay", "malayalam", + "marathi", "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", + "romanian", "russian", "serbianCyrillic", "serbianLatin", "slovak", "slovenian", "spanish", + "swedish", "tamil", "telugu", "turkish", "ukrainian", and "urdu". + :vartype language: str or + ~azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Tokens longer than the maximum length are split. Maximum token length + that can be used is 300 characters. Tokens longer than 300 characters are first split into + tokens of length 300 and then each of those tokens is split based on the max token length set. + Default is 255.""" + is_search_tokenizer: Optional[bool] = rest_field( + name="isSearchTokenizer", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how the tokenizer is used. Set to true if used as the search tokenizer, set + to false if used as the indexing tokenizer. Default is false.""" + language: Optional[Union[str, "_models.MicrosoftStemmingTokenizerLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. The default is English. Known values are: \"arabic\", \"bangla\", + \"bulgarian\", \"catalan\", \"croatian\", \"czech\", \"danish\", \"dutch\", \"english\", + \"estonian\", \"finnish\", \"french\", \"german\", \"greek\", \"gujarati\", \"hebrew\", + \"hindi\", \"hungarian\", \"icelandic\", \"indonesian\", \"italian\", \"kannada\", \"latvian\", + \"lithuanian\", \"malay\", \"malayalam\", \"marathi\", \"norwegianBokmaal\", \"polish\", + \"portuguese\", \"portugueseBrazilian\", \"punjabi\", \"romanian\", \"russian\", + \"serbianCyrillic\", \"serbianLatin\", \"slovak\", \"slovenian\", \"spanish\", \"swedish\", + \"tamil\", \"telugu\", \"turkish\", \"ukrainian\", and \"urdu\".""" + odata_type: Literal["#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + is_search_tokenizer: Optional[bool] = None, + language: Optional[Union[str, "_models.MicrosoftStemmingTokenizerLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer" # type: ignore + + +class MicrosoftLanguageTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.MicrosoftLanguageTokenizer"): + """Divides text using language-specific rules. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_token_length: The maximum token length. Tokens longer than the maximum length are + split. Maximum token length that can be used is 300 characters. Tokens longer than 300 + characters are first split into tokens of length 300 and then each of those tokens is split + based on the max token length set. Default is 255. + :vartype max_token_length: int + :ivar is_search_tokenizer: A value indicating how the tokenizer is used. Set to true if used as + the search tokenizer, set to false if used as the indexing tokenizer. Default is false. + :vartype is_search_tokenizer: bool + :ivar language: The language to use. The default is English. Known values are: "bangla", + "bulgarian", "catalan", "chineseSimplified", "chineseTraditional", "croatian", "czech", + "danish", "dutch", "english", "french", "german", "greek", "gujarati", "hindi", "icelandic", + "indonesian", "italian", "japanese", "kannada", "korean", "malay", "malayalam", "marathi", + "norwegianBokmaal", "polish", "portuguese", "portugueseBrazilian", "punjabi", "romanian", + "russian", "serbianCyrillic", "serbianLatin", "slovenian", "spanish", "swedish", "tamil", + "telugu", "thai", "ukrainian", "urdu", and "vietnamese". + :vartype language: str or ~azure.search.documents.indexes.models.MicrosoftTokenizerLanguage + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer". + :vartype odata_type: str + """ + + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Tokens longer than the maximum length are split. Maximum token length + that can be used is 300 characters. Tokens longer than 300 characters are first split into + tokens of length 300 and then each of those tokens is split based on the max token length set. + Default is 255.""" + is_search_tokenizer: Optional[bool] = rest_field( + name="isSearchTokenizer", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how the tokenizer is used. Set to true if used as the search tokenizer, set + to false if used as the indexing tokenizer. Default is false.""" + language: Optional[Union[str, "_models.MicrosoftTokenizerLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. The default is English. Known values are: \"bangla\", \"bulgarian\", + \"catalan\", \"chineseSimplified\", \"chineseTraditional\", \"croatian\", \"czech\", + \"danish\", \"dutch\", \"english\", \"french\", \"german\", \"greek\", \"gujarati\", \"hindi\", + \"icelandic\", \"indonesian\", \"italian\", \"japanese\", \"kannada\", \"korean\", \"malay\", + \"malayalam\", \"marathi\", \"norwegianBokmaal\", \"polish\", \"portuguese\", + \"portugueseBrazilian\", \"punjabi\", \"romanian\", \"russian\", \"serbianCyrillic\", + \"serbianLatin\", \"slovenian\", \"spanish\", \"swedish\", \"tamil\", \"telugu\", \"thai\", + \"ukrainian\", \"urdu\", and \"vietnamese\".""" + odata_type: Literal["#Microsoft.Azure.Search.MicrosoftLanguageTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.MicrosoftLanguageTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + max_token_length: Optional[int] = None, + is_search_tokenizer: Optional[bool] = None, + language: Optional[Union[str, "_models.MicrosoftTokenizerLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer" # type: ignore + + +class NativeBlobSoftDeleteDeletionDetectionPolicy( + DataDeletionDetectionPolicy, discriminator="#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" +): # pylint: disable=name-too-long + """Defines a data deletion detection policy utilizing Azure Blob Storage's native soft delete + feature for deletion detection. + + :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. + Required. Default value is + "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data deletion detection policy. Required. Default value + is \"#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" # type: ignore + + +class NGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.NGramTokenFilterV2"): + """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.NGramTokenFilterV2". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + odata_type: Literal["#Microsoft.Azure.Search.NGramTokenFilterV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.NGramTokenFilterV2\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NGramTokenFilterV2" # type: ignore + + +class NGramTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.NGramTokenizer"): + """Tokenizes the input into n-grams of the given size(s). This tokenizer is implemented using + Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + value of maxGram. + :vartype min_gram: int + :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :vartype max_gram: int + :ivar token_chars: Character classes to keep in the tokens. + :vartype token_chars: list[str or ~azure.search.documents.indexes.models.TokenCharacterKind] + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.NGramTokenizer". + :vartype odata_type: str + """ + + min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) + """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of + maxGram.""" + max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) + """The maximum n-gram length. Default is 2. Maximum is 300.""" + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = rest_field( + name="tokenChars", visibility=["read", "create", "update", "delete", "query"] + ) + """Character classes to keep in the tokens.""" + odata_type: Literal["#Microsoft.Azure.Search.NGramTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.NGramTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + min_gram: Optional[int] = None, + max_gram: Optional[int] = None, + token_chars: Optional[list[Union[str, "_models.TokenCharacterKind"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.NGramTokenizer" # type: ignore + + +class OcrSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Vision.OcrSkill"): + """A skill that extracts text from image files. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "af", "sq", "anp", "ar", "ast", "awa", "az", "bfy", "eu", "be", "be-cyrl", + "be-latn", "bho", "bi", "brx", "bs", "bra", "br", "bg", "bns", "bua", "ca", "ceb", "rab", "ch", + "hne", "zh-Hans", "zh-Hant", "kw", "co", "crh", "hr", "cs", "da", "prs", "dhi", "doi", "nl", + "en", "myv", "et", "fo", "fj", "fil", "fi", "fr", "fur", "gag", "gl", "de", "gil", "gon", "el", + "kl", "gvr", "ht", "hlb", "hni", "bgc", "haw", "hi", "mww", "hoc", "hu", "is", "smn", "id", + "ia", "iu", "ga", "it", "ja", "Jns", "jv", "kea", "kac", "xnr", "krc", "kaa-cyrl", "kaa", + "csb", "kk-cyrl", "kk-latn", "klr", "kha", "quc", "ko", "kfq", "kpy", "kos", "kum", "ku-arab", + "ku-latn", "kru", "ky", "lkt", "la", "lt", "dsb", "smj", "lb", "bfz", "ms", "mt", "kmj", "gv", + "mi", "mr", "mn", "cnr-cyrl", "cnr-latn", "nap", "ne", "niu", "nog", "sme", "nb", "no", "oc", + "os", "ps", "fa", "pl", "pt", "pa", "ksh", "ro", "rm", "ru", "sck", "sm", "sa", "sat", "sco", + "gd", "sr", "sr-Cyrl", "sr-Latn", "xsr", "srx", "sms", "sk", "sl", "so", "sma", "es", "sw", + "sv", "tg", "tt", "tet", "thf", "to", "tr", "tk", "tyv", "hsb", "ur", "ug", "uz-arab", + "uz-cyrl", "uz", "vo", "wae", "cy", "fy", "yua", "za", "zu", and "unk". + :vartype default_language_code: str or ~azure.search.documents.indexes.models.OcrSkillLanguage + :ivar should_detect_orientation: A value indicating to turn orientation detection on or not. + Default is false. + :vartype should_detect_orientation: bool + :ivar line_ending: Defines the sequence of characters to use between the lines of text + recognized by the OCR skill. The default value is "space". Known values are: "space", + "carriageReturn", "lineFeed", and "carriageReturnLineFeed". + :vartype line_ending: str or ~azure.search.documents.indexes.models.OcrLineEnding + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Vision.OcrSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.OcrSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"af\", + \"sq\", \"anp\", \"ar\", \"ast\", \"awa\", \"az\", \"bfy\", \"eu\", \"be\", \"be-cyrl\", + \"be-latn\", \"bho\", \"bi\", \"brx\", \"bs\", \"bra\", \"br\", \"bg\", \"bns\", \"bua\", + \"ca\", \"ceb\", \"rab\", \"ch\", \"hne\", \"zh-Hans\", \"zh-Hant\", \"kw\", \"co\", \"crh\", + \"hr\", \"cs\", \"da\", \"prs\", \"dhi\", \"doi\", \"nl\", \"en\", \"myv\", \"et\", \"fo\", + \"fj\", \"fil\", \"fi\", \"fr\", \"fur\", \"gag\", \"gl\", \"de\", \"gil\", \"gon\", \"el\", + \"kl\", \"gvr\", \"ht\", \"hlb\", \"hni\", \"bgc\", \"haw\", \"hi\", \"mww\", \"hoc\", \"hu\", + \"is\", \"smn\", \"id\", \"ia\", \"iu\", \"ga\", \"it\", \"ja\", \"Jns\", \"jv\", \"kea\", + \"kac\", \"xnr\", \"krc\", \"kaa-cyrl\", \"kaa\", \"csb\", \"kk-cyrl\", \"kk-latn\", \"klr\", + \"kha\", \"quc\", \"ko\", \"kfq\", \"kpy\", \"kos\", \"kum\", \"ku-arab\", \"ku-latn\", + \"kru\", \"ky\", \"lkt\", \"la\", \"lt\", \"dsb\", \"smj\", \"lb\", \"bfz\", \"ms\", \"mt\", + \"kmj\", \"gv\", \"mi\", \"mr\", \"mn\", \"cnr-cyrl\", \"cnr-latn\", \"nap\", \"ne\", \"niu\", + \"nog\", \"sme\", \"nb\", \"no\", \"oc\", \"os\", \"ps\", \"fa\", \"pl\", \"pt\", \"pa\", + \"ksh\", \"ro\", \"rm\", \"ru\", \"sck\", \"sm\", \"sa\", \"sat\", \"sco\", \"gd\", \"sr\", + \"sr-Cyrl\", \"sr-Latn\", \"xsr\", \"srx\", \"sms\", \"sk\", \"sl\", \"so\", \"sma\", \"es\", + \"sw\", \"sv\", \"tg\", \"tt\", \"tet\", \"thf\", \"to\", \"tr\", \"tk\", \"tyv\", \"hsb\", + \"ur\", \"ug\", \"uz-arab\", \"uz-cyrl\", \"uz\", \"vo\", \"wae\", \"cy\", \"fy\", \"yua\", + \"za\", \"zu\", and \"unk\".""" + should_detect_orientation: Optional[bool] = rest_field( + name="detectOrientation", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating to turn orientation detection on or not. Default is false.""" + line_ending: Optional[Union[str, "_models.OcrLineEnding"]] = rest_field( + name="lineEnding", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the sequence of characters to use between the lines of text recognized by the OCR + skill. The default value is \"space\". Known values are: \"space\", \"carriageReturn\", + \"lineFeed\", and \"carriageReturnLineFeed\".""" + odata_type: Literal["#Microsoft.Skills.Vision.OcrSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Vision.OcrSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.OcrSkillLanguage"]] = None, + should_detect_orientation: Optional[bool] = None, + line_ending: Optional[Union[str, "_models.OcrLineEnding"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Vision.OcrSkill" # type: ignore + + +class OutputFieldMappingEntry(_Model): + """Output field mapping for a skill. + + :ivar name: The name of the output defined by the skill. Required. + :vartype name: str + :ivar target_name: The target name of the output. It is optional and default to name. + :vartype target_name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the output defined by the skill. Required.""" + target_name: Optional[str] = rest_field( + name="targetName", visibility=["read", "create", "update", "delete", "query"] + ) + """The target name of the output. It is optional and default to name.""" + + @overload + def __init__( + self, + *, + name: str, + target_name: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PathHierarchyTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.PathHierarchyTokenizerV2"): + """Tokenizer for path-like hierarchies. This tokenizer is implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar delimiter: The delimiter character to use. Default is "/". + :vartype delimiter: str + :ivar replacement: A value that, if set, replaces the delimiter character. Default is "/". + :vartype replacement: str + :ivar max_token_length: The maximum token length. Default and maximum is 300. + :vartype max_token_length: int + :ivar reverse_token_order: A value indicating whether to generate tokens in reverse order. + Default is false. + :vartype reverse_token_order: bool + :ivar number_of_tokens_to_skip: The number of initial tokens to skip. Default is 0. + :vartype number_of_tokens_to_skip: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.PathHierarchyTokenizerV2". + :vartype odata_type: str + """ + + delimiter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The delimiter character to use. Default is \"/\".""" + replacement: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value that, if set, replaces the delimiter character. Default is \"/\".""" + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default and maximum is 300.""" + reverse_token_order: Optional[bool] = rest_field( + name="reverse", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to generate tokens in reverse order. Default is false.""" + number_of_tokens_to_skip: Optional[int] = rest_field( + name="skip", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of initial tokens to skip. Default is 0.""" + odata_type: Literal["#Microsoft.Azure.Search.PathHierarchyTokenizerV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.PathHierarchyTokenizerV2\".""" + + @overload + def __init__( + self, + *, + name: str, + delimiter: Optional[str] = None, + replacement: Optional[str] = None, + max_token_length: Optional[int] = None, + reverse_token_order: Optional[bool] = None, + number_of_tokens_to_skip: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2" # type: ignore + + +class PatternAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.PatternAnalyzer"): + """Flexibly separates text into terms via a regular expression pattern. This analyzer is + implemented using Apache Lucene. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar lower_case_terms: A value indicating whether terms should be lower-cased. Default is + true. + :vartype lower_case_terms: bool + :ivar pattern: A regular expression pattern to match token separators. Default is an expression + that matches one or more non-word characters. + :vartype pattern: str + :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", + "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". + :vartype flags: str or ~azure.search.documents.indexes.models.RegexFlags + :ivar stopwords: A list of stopwords. + :vartype stopwords: list[str] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.PatternAnalyzer". + :vartype odata_type: str + """ + + lower_case_terms: Optional[bool] = rest_field( + name="lowercase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether terms should be lower-cased. Default is true.""" + pattern: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern to match token separators. Default is an expression that matches + one or more non-word characters.""" + flags: Optional[Union[str, "_models.RegexFlags"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Regular expression flags. Known values are: \"CANON_EQ\", \"CASE_INSENSITIVE\", \"COMMENTS\", + \"DOTALL\", \"LITERAL\", \"MULTILINE\", \"UNICODE_CASE\", and \"UNIX_LINES\".""" + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stopwords.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.PatternAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + lower_case_terms: Optional[bool] = None, + pattern: Optional[str] = None, + flags: Optional[Union[str, "_models.RegexFlags"]] = None, + stopwords: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternAnalyzer" # type: ignore + + +class PatternCaptureTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.PatternCaptureTokenFilter"): + """Uses Java regexes to emit multiple tokens - one for each capture group in one or more patterns. + This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar patterns: A list of patterns to match against each token. Required. + :vartype patterns: list[str] + :ivar preserve_original: A value indicating whether to return the original token even if one of + the patterns matches. Default is true. + :vartype preserve_original: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.PatternCaptureTokenFilter". + :vartype odata_type: str + """ + + patterns: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of patterns to match against each token. Required.""" + preserve_original: Optional[bool] = rest_field( + name="preserveOriginal", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to return the original token even if one of the patterns matches. + Default is true.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternCaptureTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.PatternCaptureTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + patterns: list[str], + preserve_original: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternCaptureTokenFilter" # type: ignore + + +class PatternReplaceCharFilter(CharFilter, discriminator="#Microsoft.Azure.Search.PatternReplaceCharFilter"): + """A character filter that replaces characters in the input string. It uses a regular expression + to identify character sequences to preserve and a replacement pattern to identify characters to + replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\s+(bb)", and + replacement "$1#$2", the result would be "aa#bb aa#bb". This character filter is implemented + using Apache Lucene. + + :ivar name: The name of the char filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar pattern: A regular expression pattern. Required. + :vartype pattern: str + :ivar replacement: The replacement text. Required. + :vartype replacement: str + :ivar odata_type: A URI fragment specifying the type of char filter. Required. Default value is + "#Microsoft.Azure.Search.PatternReplaceCharFilter". + :vartype odata_type: str + """ + + pattern: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern. Required.""" + replacement: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The replacement text. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternReplaceCharFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of char filter. Required. Default value is + \"#Microsoft.Azure.Search.PatternReplaceCharFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + pattern: str, + replacement: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternReplaceCharFilter" # type: ignore + + +class PatternReplaceTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.PatternReplaceTokenFilter"): + """A character filter that replaces characters in the input string. It uses a regular expression + to identify character sequences to preserve and a replacement pattern to identify characters to + replace. For example, given the input text "aa bb aa bb", pattern "(aa)\\s+(bb)", and + replacement "$1#$2", the result would be "aa#bb aa#bb". This token filter is implemented using + Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar pattern: A regular expression pattern. Required. + :vartype pattern: str + :ivar replacement: The replacement text. Required. + :vartype replacement: str + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.PatternReplaceTokenFilter". + :vartype odata_type: str + """ + + pattern: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern. Required.""" + replacement: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The replacement text. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternReplaceTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.PatternReplaceTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + pattern: str, + replacement: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternReplaceTokenFilter" # type: ignore + + +class PatternTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.PatternTokenizer"): + """Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is + implemented using Apache Lucene. + + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar pattern: A regular expression pattern to match token separators. Default is an expression + that matches one or more non-word characters. + :vartype pattern: str + :ivar flags: Regular expression flags. Known values are: "CANON_EQ", "CASE_INSENSITIVE", + "COMMENTS", "DOTALL", "LITERAL", "MULTILINE", "UNICODE_CASE", and "UNIX_LINES". + :vartype flags: str or ~azure.search.documents.indexes.models.RegexFlags + :ivar group: The zero-based ordinal of the matching group in the regular expression pattern to + extract into tokens. Use -1 if you want to use the entire pattern to split the input into + tokens, irrespective of matching groups. Default is -1. + :vartype group: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.PatternTokenizer". + :vartype odata_type: str + """ + + pattern: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A regular expression pattern to match token separators. Default is an expression that matches + one or more non-word characters.""" + flags: Optional[Union[str, "_models.RegexFlags"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Regular expression flags. Known values are: \"CANON_EQ\", \"CASE_INSENSITIVE\", \"COMMENTS\", + \"DOTALL\", \"LITERAL\", \"MULTILINE\", \"UNICODE_CASE\", and \"UNIX_LINES\".""" + group: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The zero-based ordinal of the matching group in the regular expression pattern to extract into + tokens. Use -1 if you want to use the entire pattern to split the input into tokens, + irrespective of matching groups. Default is -1.""" + odata_type: Literal["#Microsoft.Azure.Search.PatternTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.PatternTokenizer\".""" + + @overload + def __init__( + self, + *, + name: str, + pattern: Optional[str] = None, + flags: Optional[Union[str, "_models.RegexFlags"]] = None, + group: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PatternTokenizer" # type: ignore + + +class PhoneticTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.PhoneticTokenFilter"): + """Create tokens for phonetic matches. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar encoder: The phonetic encoder to use. Default is "metaphone". Known values are: + "metaphone", "doubleMetaphone", "soundex", "refinedSoundex", "caverphone1", "caverphone2", + "cologne", "nysiis", "koelnerPhonetik", "haasePhonetik", and "beiderMorse". + :vartype encoder: str or ~azure.search.documents.indexes.models.PhoneticEncoder + :ivar replace_original_tokens: A value indicating whether encoded tokens should replace + original tokens. If false, encoded tokens are added as synonyms. Default is true. + :vartype replace_original_tokens: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.PhoneticTokenFilter". + :vartype odata_type: str + """ + + encoder: Optional[Union[str, "_models.PhoneticEncoder"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The phonetic encoder to use. Default is \"metaphone\". Known values are: \"metaphone\", + \"doubleMetaphone\", \"soundex\", \"refinedSoundex\", \"caverphone1\", \"caverphone2\", + \"cologne\", \"nysiis\", \"koelnerPhonetik\", \"haasePhonetik\", and \"beiderMorse\".""" + replace_original_tokens: Optional[bool] = rest_field( + name="replace", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether encoded tokens should replace original tokens. If false, encoded + tokens are added as synonyms. Default is true.""" + odata_type: Literal["#Microsoft.Azure.Search.PhoneticTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.PhoneticTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + encoder: Optional[Union[str, "_models.PhoneticEncoder"]] = None, + replace_original_tokens: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.PhoneticTokenFilter" # type: ignore + + +class PIIDetectionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.PIIDetectionSkill"): + """Using the Text Analytics API, extracts personal information from an input text and gives you + the option of masking it. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose + confidence score is greater than the value specified. If not set (default), or if explicitly + set to null, all entities will be included. + :vartype minimum_precision: float + :ivar masking_mode: A parameter that provides various ways to mask the personal information + detected in the input text. Default is 'none'. Known values are: "none" and "replace". + :vartype masking_mode: str or + ~azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode + :ivar mask: The character used to mask the text if the maskingMode parameter is set to replace. + Default is '*'. + :vartype mask: str + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar pii_categories: A list of PII entity categories that should be extracted and masked. + :vartype pii_categories: list[str] + :ivar domain: If specified, will set the PII domain to include only a subset of the entity + categories. Possible values include: 'phi', 'none'. Default is 'none'. + :vartype domain: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.PIIDetectionSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + minimum_precision: Optional[float] = rest_field( + name="minimumPrecision", visibility=["read", "create", "update", "delete", "query"] + ) + """A value between 0 and 1 that be used to only include entities whose confidence score is greater + than the value specified. If not set (default), or if explicitly set to null, all entities will + be included.""" + masking_mode: Optional[Union[str, "_models.PIIDetectionSkillMaskingMode"]] = rest_field( + name="maskingMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A parameter that provides various ways to mask the personal information detected in the input + text. Default is 'none'. Known values are: \"none\" and \"replace\".""" + mask: Optional[str] = rest_field( + name="maskingCharacter", visibility=["read", "create", "update", "delete", "query"] + ) + """The character used to mask the text if the maskingMode parameter is set to replace. Default is + '*'.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + pii_categories: Optional[list[str]] = rest_field( + name="piiCategories", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of PII entity categories that should be extracted and masked.""" + domain: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """If specified, will set the PII domain to include only a subset of the entity categories. + Possible values include: 'phi', 'none'. Default is 'none'.""" + odata_type: Literal["#Microsoft.Skills.Text.PIIDetectionSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.PIIDetectionSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[str] = None, + minimum_precision: Optional[float] = None, + masking_mode: Optional[Union[str, "_models.PIIDetectionSkillMaskingMode"]] = None, + mask: Optional[str] = None, + model_version: Optional[str] = None, + pii_categories: Optional[list[str]] = None, + domain: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.PIIDetectionSkill" # type: ignore + + +class RescoringOptions(_Model): + """Contains the options for rescoring. + + :ivar enable_rescoring: If set to true, after the initial search on the compressed vectors, the + similarity scores are recalculated using the full-precision vectors. This will improve recall + at the expense of latency. + :vartype enable_rescoring: bool + :ivar default_oversampling: Default oversampling factor. Oversampling retrieves a greater set + of potential documents to offset the resolution loss due to quantization. This increases the + set of results that will be rescored on full-precision vectors. Minimum value is 1, meaning no + oversampling (1x). This parameter can only be set when 'enableRescoring' is true. Higher values + improve recall at the expense of latency. + :vartype default_oversampling: float + :ivar rescore_storage_method: Controls the storage method for original vectors. This setting is + immutable. Known values are: "preserveOriginals" and "discardOriginals". + :vartype rescore_storage_method: str or + ~azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod + """ + + enable_rescoring: Optional[bool] = rest_field( + name="enableRescoring", visibility=["read", "create", "update", "delete", "query"] + ) + """If set to true, after the initial search on the compressed vectors, the similarity scores are + recalculated using the full-precision vectors. This will improve recall at the expense of + latency.""" + default_oversampling: Optional[float] = rest_field( + name="defaultOversampling", visibility=["read", "create", "update", "delete", "query"] + ) + """Default oversampling factor. Oversampling retrieves a greater set of potential documents to + offset the resolution loss due to quantization. This increases the set of results that will be + rescored on full-precision vectors. Minimum value is 1, meaning no oversampling (1x). This + parameter can only be set when 'enableRescoring' is true. Higher values improve recall at the + expense of latency.""" + rescore_storage_method: Optional[Union[str, "_models.VectorSearchCompressionRescoreStorageMethod"]] = rest_field( + name="rescoreStorageMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the storage method for original vectors. This setting is immutable. Known values are: + \"preserveOriginals\" and \"discardOriginals\".""" + + @overload + def __init__( + self, + *, + enable_rescoring: Optional[bool] = None, + default_oversampling: Optional[float] = None, + rescore_storage_method: Optional[Union[str, "_models.VectorSearchCompressionRescoreStorageMethod"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ResourceCounter(_Model): + """Represents a resource's usage and quota. + + :ivar usage: The resource usage amount. Required. + :vartype usage: int + :ivar quota: The resource amount quota. + :vartype quota: int + """ + + usage: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The resource usage amount. Required.""" + quota: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The resource amount quota.""" + + @overload + def __init__( + self, + *, + usage: int, + quota: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ScalarQuantizationCompression(VectorSearchCompression, discriminator="scalarQuantization"): + """Contains configuration options specific to the scalar quantization compression method used + during indexing and querying. + + :ivar compression_name: The name to associate with this particular configuration. Required. + :vartype compression_name: str + :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated + using compressed vectors are obtained, they will be reranked again by recalculating the + full-precision similarity scores. This will improve recall at the expense of latency. + :vartype rerank_with_original_vectors: bool + :ivar default_oversampling: Default oversampling factor. Oversampling will internally request + more documents (specified by this multiplier) in the initial search. This increases the set of + results that will be reranked using recomputed similarity scores from full-precision vectors. + Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when + rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. + :vartype default_oversampling: float + :ivar rescoring_options: Contains the options for rescoring. + :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions + :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the + vectors reduces the size of the vectors and the amount of data that needs to be transferred + during search. This can save storage cost and improve search performance at the expense of + recall. It should be only used for embeddings trained with Matryoshka Representation Learning + (MRL) such as OpenAI text-embedding-3-large (small). The default value is null, which means no + truncation. + :vartype truncation_dimension: int + :ivar parameters: Contains the parameters specific to Scalar Quantization. + :vartype parameters: ~azure.search.documents.indexes.models.ScalarQuantizationParameters + :ivar kind: The name of the kind of compression method being configured for use with vector + search. Required. Scalar Quantization, a type of compression method. In scalar quantization, + the original vectors values are compressed to a narrower type by discretizing and representing + each component of a vector using a reduced set of quantized values, thereby reducing the + overall data size. + :vartype kind: str or ~azure.search.documents.indexes.models.SCALAR_QUANTIZATION + """ + + parameters: Optional["_models.ScalarQuantizationParameters"] = rest_field( + name="scalarQuantizationParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains the parameters specific to Scalar Quantization.""" + kind: Literal[VectorSearchCompressionKind.SCALAR_QUANTIZATION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of compression method being configured for use with vector search. + Required. Scalar Quantization, a type of compression method. In scalar quantization, the + original vectors values are compressed to a narrower type by discretizing and representing each + component of a vector using a reduced set of quantized values, thereby reducing the overall + data size.""" + + @overload + def __init__( + self, + *, + compression_name: str, + rerank_with_original_vectors: Optional[bool] = None, + default_oversampling: Optional[float] = None, + rescoring_options: Optional["_models.RescoringOptions"] = None, + truncation_dimension: Optional[int] = None, + parameters: Optional["_models.ScalarQuantizationParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchCompressionKind.SCALAR_QUANTIZATION # type: ignore + + +class ScalarQuantizationParameters(_Model): + """Contains the parameters specific to Scalar Quantization. + + :ivar quantized_data_type: The quantized data type of compressed vector values. "int8" + :vartype quantized_data_type: str or + ~azure.search.documents.indexes.models.VectorSearchCompressionTarget + """ + + quantized_data_type: Optional[Union[str, "_models.VectorSearchCompressionTarget"]] = rest_field( + name="quantizedDataType", visibility=["read", "create", "update", "delete", "query"] + ) + """The quantized data type of compressed vector values. \"int8\"""" + + @overload + def __init__( + self, + *, + quantized_data_type: Optional[Union[str, "_models.VectorSearchCompressionTarget"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ScoringProfile(_Model): + """Defines parameters for a search index that influence scoring in search queries. + + :ivar name: The name of the scoring profile. Required. + :vartype name: str + :ivar text_weights: Parameters that boost scoring based on text matches in certain index + fields. + :vartype text_weights: ~azure.search.documents.indexes.models.TextWeights + :ivar functions: The collection of functions that influence the scoring of documents. + :vartype functions: list[~azure.search.documents.indexes.models.ScoringFunction] + :ivar function_aggregation: A value indicating how the results of individual scoring functions + should be combined. Defaults to "Sum". Ignored if there are no scoring functions. Known values + are: "sum", "average", "minimum", "maximum", and "firstMatching". + :vartype function_aggregation: str or + ~azure.search.documents.indexes.models.ScoringFunctionAggregation + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the scoring profile. Required.""" + text_weights: Optional["_models.TextWeights"] = rest_field( + name="text", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameters that boost scoring based on text matches in certain index fields.""" + functions: Optional[list["_models.ScoringFunction"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The collection of functions that influence the scoring of documents.""" + function_aggregation: Optional[Union[str, "_models.ScoringFunctionAggregation"]] = rest_field( + name="functionAggregation", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating how the results of individual scoring functions should be combined. Defaults + to \"Sum\". Ignored if there are no scoring functions. Known values are: \"sum\", \"average\", + \"minimum\", \"maximum\", and \"firstMatching\".""" + + @overload + def __init__( + self, + *, + name: str, + text_weights: Optional["_models.TextWeights"] = None, + functions: Optional[list["_models.ScoringFunction"]] = None, + function_aggregation: Optional[Union[str, "_models.ScoringFunctionAggregation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchAlias(_Model): + """Represents an index alias, which describes a mapping from the alias name to an index. The alias + name can be used in place of the index name for supported operations. + + :ivar name: The name of the alias. Required. + :vartype name: str + :ivar indexes: The name of the index this alias maps to. Only one index name may be specified. + Required. + :vartype indexes: list[str] + :ivar e_tag: The ETag of the alias. + :vartype e_tag: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the alias. Required.""" + indexes: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the index this alias maps to. Only one index name may be specified. Required.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the alias.""" + + @overload + def __init__( + self, + *, + name: str, + indexes: list[str], + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchField(_Model): + """Represents a field in an index definition, which describes the name, data type, and search + behavior of a field. + + :ivar name: The name of the field, which must be unique within the fields collection of the + index or parent field. Required. + :vartype name: str + :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", + "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", + "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". + :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType + :ivar key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type Edm.String. Key fields can be used to look up documents directly and update or delete + specific documents. Default is false for simple fields and null for complex fields. + :vartype key: bool + :ivar retrievable: A value indicating whether the field can be returned in a search result. You + can disable this option if you want to use a field (for example, margin) as a filter, sorting, + or scoring mechanism but do not want the field to be visible to the end user. This property + must be true for key fields, and it must be null for complex fields. This property can be + changed on existing fields. Enabling this property does not cause any increase in index storage + requirements. Default is true for simple fields, false for vector fields, and null for complex + fields. + :vartype retrievable: bool + :ivar stored: An immutable value indicating whether the field will be persisted separately on + disk to be returned in a search result. You can disable this option if you don't plan to return + the field contents in a search response to save on storage overhead. This can only be set + during index creation and only for vector fields. This property cannot be changed for existing + fields or set as false for new fields. If this property is set as false, the property + 'retrievable' must also be set to false. This property must be true or unset for key fields, + for new fields, and for non-vector fields, and it must be null for complex fields. Disabling + this property will reduce index storage requirements. The default is true for vector fields. + :vartype stored: bool + :ivar searchable: A value indicating whether the field is full-text searchable. This means it + will undergo analysis such as word-breaking during indexing. If you set a searchable field to a + value like "sunny day", internally it will be split into the individual tokens "sunny" and + "day". This enables full-text searches for these terms. Fields of type Edm.String or + Collection(Edm.String) are searchable by default. This property must be false for simple fields + of other non-string data types, and it must be null for complex fields. Note: searchable fields + consume extra space in your index to accommodate additional tokenized versions of the field + value for full-text searches. If you want to save space in your index and you don't need a + field to be included in searches, set searchable to false. + :vartype searchable: bool + :ivar filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields of type + Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so + comparisons are for exact matches only. For example, if you set such a field f to "sunny day", + $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property + must be null for complex fields. Default is true for simple fields and null for complex fields. + :vartype filterable: bool + :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default, the search engine sorts results by score, but in many experiences + users will want to sort by fields in the documents. A simple field can be sortable only if it + is single-valued (it has a single value in the scope of the parent document). Simple collection + fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex + collections are also multi-valued, and therefore cannot be sortable. This is true whether it's + an immediate parent field, or an ancestor field, that's the complex collection. Complex fields + cannot be sortable and the sortable property must be null for such fields. The default for + sortable is true for single-valued simple fields, false for multi-valued simple fields, and + null for complex fields. + :vartype sortable: bool + :ivar facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or + Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple + fields. + :vartype facetable: bool + :ivar permission_filter: A value indicating whether the field should be used as a permission + filter. Known values are: "userIds", "groupIds", and "rbacScope". + :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter + :ivar analyzer: The name of the analyzer to use for the field. This option can be used only + with searchable fields and it can't be set together with either searchAnalyzer or + indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null + for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", + "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar search_analyzer: The name of the analyzer used at search time for the field. This option + can be used only with searchable fields. It must be set together with indexAnalyzer and it + cannot be set together with the analyzer option. This property cannot be set to the name of a + language analyzer; use the analyzer property instead if you need a language analyzer. This + analyzer can be updated on an existing field. Must be null for complex fields. Known values + are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", + "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", + "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", + "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", + "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", + "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", + "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", + "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", + "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", + "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", + "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype search_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar index_analyzer: The name of the analyzer used at indexing time for the field. This option + can be used only with searchable fields. It must be set together with searchAnalyzer and it + cannot be set together with the analyzer option. This property cannot be set to the name of a + language analyzer; use the analyzer property instead if you need a language analyzer. Once the + analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known + values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", + "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype index_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar normalizer: The name of the normalizer to use for the field. This option can be used only + with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it + cannot be changed for the field. Must be null for complex fields. Known values are: + "asciifolding", "elision", "lowercase", "standard", and "uppercase". + :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :ivar vector_search_dimensions: The dimensionality of the vector field. + :vartype vector_search_dimensions: int + :ivar vector_search_profile_name: The name of the vector search profile that specifies the + algorithm and vectorizer to use when searching the vector field. + :vartype vector_search_profile_name: str + :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" + :vartype vector_encoding_format: str or + ~azure.search.documents.indexes.models.VectorEncodingFormat + :ivar synonym_maps: A list of the names of synonym maps to associate with this field. This + option can be used only with searchable fields. Currently only one synonym map per field is + supported. Assigning a synonym map to a field ensures that query terms targeting that field are + expanded at query-time using the rules in the synonym map. This attribute can be changed on + existing fields. Must be null or an empty collection for complex fields. + :vartype synonym_maps: list[str] + :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or + Collection(Edm.ComplexType). Must be null or empty for simple fields. + :vartype fields: list[~azure.search.documents.indexes.models.SearchField] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the field, which must be unique within the fields collection of the index or parent + field. Required.""" + type: Union[str, "_models.SearchFieldDataType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The data type of the field. Required. Known values are: \"Edm.String\", \"Edm.Int32\", + \"Edm.Int64\", \"Edm.Double\", \"Edm.Boolean\", \"Edm.DateTimeOffset\", \"Edm.GeographyPoint\", + \"Edm.ComplexType\", \"Edm.Single\", \"Edm.Half\", \"Edm.Int16\", \"Edm.SByte\", and + \"Edm.Byte\".""" + key: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the field uniquely identifies documents in the index. Exactly one + top-level field in each index must be chosen as the key field and it must be of type + Edm.String. Key fields can be used to look up documents directly and update or delete specific + documents. Default is false for simple fields and null for complex fields.""" + retrievable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the field can be returned in a search result. You can disable this + option if you want to use a field (for example, margin) as a filter, sorting, or scoring + mechanism but do not want the field to be visible to the end user. This property must be true + for key fields, and it must be null for complex fields. This property can be changed on + existing fields. Enabling this property does not cause any increase in index storage + requirements. Default is true for simple fields, false for vector fields, and null for complex + fields.""" + stored: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An immutable value indicating whether the field will be persisted separately on disk to be + returned in a search result. You can disable this option if you don't plan to return the field + contents in a search response to save on storage overhead. This can only be set during index + creation and only for vector fields. This property cannot be changed for existing fields or set + as false for new fields. If this property is set as false, the property 'retrievable' must also + be set to false. This property must be true or unset for key fields, for new fields, and for + non-vector fields, and it must be null for complex fields. Disabling this property will reduce + index storage requirements. The default is true for vector fields.""" + searchable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the field is full-text searchable. This means it will undergo + analysis such as word-breaking during indexing. If you set a searchable field to a value like + \"sunny day\", internally it will be split into the individual tokens \"sunny\" and \"day\". + This enables full-text searches for these terms. Fields of type Edm.String or + Collection(Edm.String) are searchable by default. This property must be false for simple fields + of other non-string data types, and it must be null for complex fields. Note: searchable fields + consume extra space in your index to accommodate additional tokenized versions of the field + value for full-text searches. If you want to save space in your index and you don't need a + field to be included in searches, set searchable to false.""" + filterable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether to enable the field to be referenced in $filter queries. filterable + differs from searchable in how strings are handled. Fields of type Edm.String or + Collection(Edm.String) that are filterable do not undergo word-breaking, so comparisons are for + exact matches only. For example, if you set such a field f to \"sunny day\", $filter=f eq + 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property must be null for + complex fields. Default is true for simple fields and null for complex fields.""" + sortable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether to enable the field to be referenced in $orderby expressions. By + default, the search engine sorts results by score, but in many experiences users will want to + sort by fields in the documents. A simple field can be sortable only if it is single-valued (it + has a single value in the scope of the parent document). Simple collection fields cannot be + sortable, since they are multi-valued. Simple sub-fields of complex collections are also + multi-valued, and therefore cannot be sortable. This is true whether it's an immediate parent + field, or an ancestor field, that's the complex collection. Complex fields cannot be sortable + and the sortable property must be null for such fields. The default for sortable is true for + single-valued simple fields, false for multi-valued simple fields, and null for complex fields.""" + facetable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether to enable the field to be referenced in facet queries. Typically + used in a presentation of search results that includes hit count by category (for example, + search for digital cameras and see hits by brand, by megapixels, by price, and so on). This + property must be null for complex fields. Fields of type Edm.GeographyPoint or + Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple + fields.""" + permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = rest_field( + name="permissionFilter", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the field should be used as a permission filter. Known values are: + \"userIds\", \"groupIds\", and \"rbacScope\".""" + analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer to use for the field. This option can be used only with searchable + fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once the + analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known + values are: \"ar.microsoft\", \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", \"eu.lucene\", + \"bg.microsoft\", \"bg.lucene\", \"ca.microsoft\", \"ca.lucene\", \"zh-Hans.microsoft\", + \"zh-Hans.lucene\", \"zh-Hant.microsoft\", \"zh-Hant.lucene\", \"hr.microsoft\", + \"cs.microsoft\", \"cs.lucene\", \"da.microsoft\", \"da.lucene\", \"nl.microsoft\", + \"nl.lucene\", \"en.microsoft\", \"en.lucene\", \"et.microsoft\", \"fi.microsoft\", + \"fi.lucene\", \"fr.microsoft\", \"fr.lucene\", \"gl.lucene\", \"de.microsoft\", \"de.lucene\", + \"el.microsoft\", \"el.lucene\", \"gu.microsoft\", \"he.microsoft\", \"hi.microsoft\", + \"hi.lucene\", \"hu.microsoft\", \"hu.lucene\", \"is.microsoft\", \"id.microsoft\", + \"id.lucene\", \"ga.lucene\", \"it.microsoft\", \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", + \"kn.microsoft\", \"ko.microsoft\", \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", + \"lt.microsoft\", \"ml.microsoft\", \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", + \"no.lucene\", \"fa.lucene\", \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", + \"pt-BR.lucene\", \"pt-PT.microsoft\", \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", + \"ro.lucene\", \"ru.microsoft\", \"ru.lucene\", \"sr-cyrillic.microsoft\", + \"sr-latin.microsoft\", \"sk.microsoft\", \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", + \"sv.microsoft\", \"sv.lucene\", \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", + \"th.lucene\", \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", + \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", + \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" + search_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="searchAnalyzer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer used at search time for the field. This option can be used only with + searchable fields. It must be set together with indexAnalyzer and it cannot be set together + with the analyzer option. This property cannot be set to the name of a language analyzer; use + the analyzer property instead if you need a language analyzer. This analyzer can be updated on + an existing field. Must be null for complex fields. Known values are: \"ar.microsoft\", + \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", \"eu.lucene\", \"bg.microsoft\", \"bg.lucene\", + \"ca.microsoft\", \"ca.lucene\", \"zh-Hans.microsoft\", \"zh-Hans.lucene\", + \"zh-Hant.microsoft\", \"zh-Hant.lucene\", \"hr.microsoft\", \"cs.microsoft\", \"cs.lucene\", + \"da.microsoft\", \"da.lucene\", \"nl.microsoft\", \"nl.lucene\", \"en.microsoft\", + \"en.lucene\", \"et.microsoft\", \"fi.microsoft\", \"fi.lucene\", \"fr.microsoft\", + \"fr.lucene\", \"gl.lucene\", \"de.microsoft\", \"de.lucene\", \"el.microsoft\", \"el.lucene\", + \"gu.microsoft\", \"he.microsoft\", \"hi.microsoft\", \"hi.lucene\", \"hu.microsoft\", + \"hu.lucene\", \"is.microsoft\", \"id.microsoft\", \"id.lucene\", \"ga.lucene\", + \"it.microsoft\", \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", \"kn.microsoft\", + \"ko.microsoft\", \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", \"lt.microsoft\", + \"ml.microsoft\", \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", \"no.lucene\", + \"fa.lucene\", \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", \"pt-BR.lucene\", + \"pt-PT.microsoft\", \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", \"ro.lucene\", + \"ru.microsoft\", \"ru.lucene\", \"sr-cyrillic.microsoft\", \"sr-latin.microsoft\", + \"sk.microsoft\", \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", \"sv.microsoft\", + \"sv.lucene\", \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", \"th.lucene\", + \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", + \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", + \"stop\", and \"whitespace\".""" + index_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="indexAnalyzer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the analyzer used at indexing time for the field. This option can be used only with + searchable fields. It must be set together with searchAnalyzer and it cannot be set together + with the analyzer option. This property cannot be set to the name of a language analyzer; use + the analyzer property instead if you need a language analyzer. Once the analyzer is chosen, it + cannot be changed for the field. Must be null for complex fields. Known values are: + \"ar.microsoft\", \"ar.lucene\", \"hy.lucene\", \"bn.microsoft\", \"eu.lucene\", + \"bg.microsoft\", \"bg.lucene\", \"ca.microsoft\", \"ca.lucene\", \"zh-Hans.microsoft\", + \"zh-Hans.lucene\", \"zh-Hant.microsoft\", \"zh-Hant.lucene\", \"hr.microsoft\", + \"cs.microsoft\", \"cs.lucene\", \"da.microsoft\", \"da.lucene\", \"nl.microsoft\", + \"nl.lucene\", \"en.microsoft\", \"en.lucene\", \"et.microsoft\", \"fi.microsoft\", + \"fi.lucene\", \"fr.microsoft\", \"fr.lucene\", \"gl.lucene\", \"de.microsoft\", \"de.lucene\", + \"el.microsoft\", \"el.lucene\", \"gu.microsoft\", \"he.microsoft\", \"hi.microsoft\", + \"hi.lucene\", \"hu.microsoft\", \"hu.lucene\", \"is.microsoft\", \"id.microsoft\", + \"id.lucene\", \"ga.lucene\", \"it.microsoft\", \"it.lucene\", \"ja.microsoft\", \"ja.lucene\", + \"kn.microsoft\", \"ko.microsoft\", \"ko.lucene\", \"lv.microsoft\", \"lv.lucene\", + \"lt.microsoft\", \"ml.microsoft\", \"ms.microsoft\", \"mr.microsoft\", \"nb.microsoft\", + \"no.lucene\", \"fa.lucene\", \"pl.microsoft\", \"pl.lucene\", \"pt-BR.microsoft\", + \"pt-BR.lucene\", \"pt-PT.microsoft\", \"pt-PT.lucene\", \"pa.microsoft\", \"ro.microsoft\", + \"ro.lucene\", \"ru.microsoft\", \"ru.lucene\", \"sr-cyrillic.microsoft\", + \"sr-latin.microsoft\", \"sk.microsoft\", \"sl.microsoft\", \"es.microsoft\", \"es.lucene\", + \"sv.microsoft\", \"sv.lucene\", \"ta.microsoft\", \"te.microsoft\", \"th.microsoft\", + \"th.lucene\", \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", + \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", + \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" + normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the normalizer to use for the field. This option can be used only with fields with + filterable, sortable, or facetable enabled. Once the normalizer is chosen, it cannot be changed + for the field. Must be null for complex fields. Known values are: \"asciifolding\", + \"elision\", \"lowercase\", \"standard\", and \"uppercase\".""" + vector_search_dimensions: Optional[int] = rest_field( + name="dimensions", visibility=["read", "create", "update", "delete", "query"] + ) + """The dimensionality of the vector field.""" + vector_search_profile_name: Optional[str] = rest_field( + name="vectorSearchProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the vector search profile that specifies the algorithm and vectorizer to use when + searching the vector field.""" + vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = rest_field( + name="vectorEncoding", visibility=["read", "create", "update", "delete", "query"] + ) + """The encoding format to interpret the field contents. \"packedBit\"""" + synonym_maps: Optional[list[str]] = rest_field( + name="synonymMaps", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of the names of synonym maps to associate with this field. This option can be used only + with searchable fields. Currently only one synonym map per field is supported. Assigning a + synonym map to a field ensures that query terms targeting that field are expanded at query-time + using the rules in the synonym map. This attribute can be changed on existing fields. Must be + null or an empty collection for complex fields.""" + fields: Optional[list["_models.SearchField"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of sub-fields if this is a field of type Edm.ComplexType or Collection(Edm.ComplexType). + Must be null or empty for simple fields.""" + + @overload + def __init__( + self, + *, + name: str, + type: Union[str, "_models.SearchFieldDataType"], + key: Optional[bool] = None, + retrievable: Optional[bool] = None, + stored: Optional[bool] = None, + searchable: Optional[bool] = None, + filterable: Optional[bool] = None, + sortable: Optional[bool] = None, + facetable: Optional[bool] = None, + permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = None, + analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + search_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + index_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, + vector_search_dimensions: Optional[int] = None, + vector_search_profile_name: Optional[str] = None, + vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = None, + synonym_maps: Optional[list[str]] = None, + fields: Optional[list["_models.SearchField"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndex(_Model): + """Represents a search index definition, which describes the fields and search behavior of an + index. + + :ivar name: The name of the index. Required. + :vartype name: str + :ivar description: The description of the index. + :vartype description: str + :ivar fields: The fields of the index. Required. + :vartype fields: list[~azure.search.documents.indexes.models.SearchField] + :ivar scoring_profiles: The scoring profiles for the index. + :vartype scoring_profiles: list[~azure.search.documents.indexes.models.ScoringProfile] + :ivar default_scoring_profile: The name of the scoring profile to use if none is specified in + the query. If this property is not set and no scoring profile is specified in the query, then + default scoring (tf-idf) will be used. + :vartype default_scoring_profile: str + :ivar cors_options: Options to control Cross-Origin Resource Sharing (CORS) for the index. + :vartype cors_options: ~azure.search.documents.indexes.models.CorsOptions + :ivar suggesters: The suggesters for the index. + :vartype suggesters: list[~azure.search.documents.indexes.models.SearchSuggester] + :ivar analyzers: The analyzers for the index. + :vartype analyzers: list[~azure.search.documents.indexes.models.LexicalAnalyzer] + :ivar tokenizers: The tokenizers for the index. + :vartype tokenizers: list[~azure.search.documents.indexes.models.LexicalTokenizer] + :ivar token_filters: The token filters for the index. + :vartype token_filters: list[~azure.search.documents.indexes.models.TokenFilter] + :ivar char_filters: The character filters for the index. + :vartype char_filters: list[~azure.search.documents.indexes.models.CharFilter] + :ivar normalizers: The normalizers for the index. + :vartype normalizers: list[~azure.search.documents.indexes.models.LexicalNormalizer] + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your data when you + want full assurance that no one, not even Microsoft, can decrypt your data. Once you have + encrypted your data, it will always remain encrypted. The search service will ignore attempts + to set this property to null. You can change this property as needed if you want to rotate your + encryption key; Your data will be unaffected. Encryption with customer-managed keys is not + available for free search services, and is only available for paid services created on or after + January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar similarity: The type of similarity algorithm to be used when scoring and ranking the + documents matching a search query. The similarity algorithm can only be defined at index + creation time and cannot be modified on existing indexes. If null, the ClassicSimilarity + algorithm is used. + :vartype similarity: ~azure.search.documents.indexes.models.SimilarityAlgorithm + :ivar semantic_search: Defines parameters for a search index that influence semantic + capabilities. + :vartype semantic_search: ~azure.search.documents.indexes.models.SemanticSearch + :ivar vector_search: Contains configuration options related to vector search. + :vartype vector_search: ~azure.search.documents.indexes.models.VectorSearch + :ivar permission_filter_option: A value indicating whether permission filtering is enabled for + the index. Known values are: "enabled" and "disabled". + :vartype permission_filter_option: str or + ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption + :ivar e_tag: The ETag of the index. + :vartype e_tag: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the index. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the index.""" + fields: list["_models.SearchField"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The fields of the index. Required.""" + scoring_profiles: Optional[list["_models.ScoringProfile"]] = rest_field( + name="scoringProfiles", visibility=["read", "create", "update", "delete", "query"] + ) + """The scoring profiles for the index.""" + default_scoring_profile: Optional[str] = rest_field( + name="defaultScoringProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the scoring profile to use if none is specified in the query. If this property is + not set and no scoring profile is specified in the query, then default scoring (tf-idf) will be + used.""" + cors_options: Optional["_models.CorsOptions"] = rest_field( + name="corsOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Options to control Cross-Origin Resource Sharing (CORS) for the index.""" + suggesters: Optional[list["_models.SearchSuggester"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The suggesters for the index.""" + analyzers: Optional[list["_models.LexicalAnalyzer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The analyzers for the index.""" + tokenizers: Optional[list["_models.LexicalTokenizer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The tokenizers for the index.""" + token_filters: Optional[list["_models.TokenFilter"]] = rest_field( + name="tokenFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """The token filters for the index.""" + char_filters: Optional[list["_models.CharFilter"]] = rest_field( + name="charFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """The character filters for the index.""" + normalizers: Optional[list["_models.LexicalNormalizer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The normalizers for the index.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your data when you want full assurance + that no one, not even Microsoft, can decrypt your data. Once you have encrypted your data, it + will always remain encrypted. The search service will ignore attempts to set this property to + null. You can change this property as needed if you want to rotate your encryption key; Your + data will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019.""" + similarity: Optional["_models.SimilarityAlgorithm"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of similarity algorithm to be used when scoring and ranking the documents matching a + search query. The similarity algorithm can only be defined at index creation time and cannot be + modified on existing indexes. If null, the ClassicSimilarity algorithm is used.""" + semantic_search: Optional["_models.SemanticSearch"] = rest_field( + name="semantic", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines parameters for a search index that influence semantic capabilities.""" + vector_search: Optional["_models.VectorSearch"] = rest_field( + name="vectorSearch", visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options related to vector search.""" + permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = rest_field( + name="permissionFilterOption", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether permission filtering is enabled for the index. Known values are: + \"enabled\" and \"disabled\".""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the index.""" + + @overload + def __init__( + self, + *, + name: str, + fields: list["_models.SearchField"], + description: Optional[str] = None, + scoring_profiles: Optional[list["_models.ScoringProfile"]] = None, + default_scoring_profile: Optional[str] = None, + cors_options: Optional["_models.CorsOptions"] = None, + suggesters: Optional[list["_models.SearchSuggester"]] = None, + analyzers: Optional[list["_models.LexicalAnalyzer"]] = None, + tokenizers: Optional[list["_models.LexicalTokenizer"]] = None, + token_filters: Optional[list["_models.TokenFilter"]] = None, + char_filters: Optional[list["_models.CharFilter"]] = None, + normalizers: Optional[list["_models.LexicalNormalizer"]] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + similarity: Optional["_models.SimilarityAlgorithm"] = None, + semantic_search: Optional["_models.SemanticSearch"] = None, + vector_search: Optional["_models.VectorSearch"] = None, + permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexer(_Model): + """Represents an indexer. + + :ivar name: The name of the indexer. Required. + :vartype name: str + :ivar description: The description of the indexer. + :vartype description: str + :ivar data_source_name: The name of the datasource from which this indexer reads data. + Required. + :vartype data_source_name: str + :ivar skillset_name: The name of the skillset executing with this indexer. + :vartype skillset_name: str + :ivar target_index_name: The name of the index to which this indexer writes data. Required. + :vartype target_index_name: str + :ivar schedule: The schedule for this indexer. + :vartype schedule: ~azure.search.documents.indexes.models.IndexingSchedule + :ivar parameters: Parameters for indexer execution. + :vartype parameters: ~azure.search.documents.indexes.models.IndexingParameters + :ivar field_mappings: Defines mappings between fields in the data source and corresponding + target fields in the index. + :vartype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] + :ivar output_field_mappings: Output field mappings are applied after enrichment and immediately + before indexing. + :vartype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] + :ivar is_disabled: A value indicating whether the indexer is disabled. Default is false. + :vartype is_disabled: bool + :ivar e_tag: The ETag of the indexer. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your indexer + definition (as well as indexer execution status) when you want full assurance that no one, not + even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will + always remain encrypted. The search service will ignore attempts to set this property to null. + You can change this property as needed if you want to rotate your encryption key; Your indexer + definition (and indexer execution status) will be unaffected. Encryption with customer-managed + keys is not available for free search services, and is only available for paid services created + on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar cache: Adds caching to an enrichment pipeline to allow for incremental modification steps + without having to rebuild the index every time. + :vartype cache: ~azure.search.documents.indexes.models.SearchIndexerCache + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the indexer. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the indexer.""" + data_source_name: str = rest_field( + name="dataSourceName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the datasource from which this indexer reads data. Required.""" + skillset_name: Optional[str] = rest_field( + name="skillsetName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the skillset executing with this indexer.""" + target_index_name: str = rest_field( + name="targetIndexName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the index to which this indexer writes data. Required.""" + schedule: Optional["_models.IndexingSchedule"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The schedule for this indexer.""" + parameters: Optional["_models.IndexingParameters"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Parameters for indexer execution.""" + field_mappings: Optional[list["_models.FieldMapping"]] = rest_field( + name="fieldMappings", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines mappings between fields in the data source and corresponding target fields in the + index.""" + output_field_mappings: Optional[list["_models.FieldMapping"]] = rest_field( + name="outputFieldMappings", visibility=["read", "create", "update", "delete", "query"] + ) + """Output field mappings are applied after enrichment and immediately before indexing.""" + is_disabled: Optional[bool] = rest_field( + name="disabled", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the indexer is disabled. Default is false.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the indexer.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your indexer definition (as well as + indexer execution status) when you want full assurance that no one, not even Microsoft, can + decrypt them. Once you have encrypted your indexer definition, it will always remain encrypted. + The search service will ignore attempts to set this property to null. You can change this + property as needed if you want to rotate your encryption key; Your indexer definition (and + indexer execution status) will be unaffected. Encryption with customer-managed keys is not + available for free search services, and is only available for paid services created on or after + January 1, 2019.""" + cache: Optional["_models.SearchIndexerCache"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Adds caching to an enrichment pipeline to allow for incremental modification steps without + having to rebuild the index every time.""" + + @overload + def __init__( + self, + *, + name: str, + data_source_name: str, + target_index_name: str, + description: Optional[str] = None, + skillset_name: Optional[str] = None, + schedule: Optional["_models.IndexingSchedule"] = None, + parameters: Optional["_models.IndexingParameters"] = None, + field_mappings: Optional[list["_models.FieldMapping"]] = None, + output_field_mappings: Optional[list["_models.FieldMapping"]] = None, + is_disabled: Optional[bool] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + cache: Optional["_models.SearchIndexerCache"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerCache(_Model): + """The type of the cache. + + :ivar storage_connection_string: The connection string to the storage account where the cache + data will be persisted. + :vartype storage_connection_string: str + :ivar enable_reprocessing: Specifies whether incremental reprocessing is enabled. + :vartype enable_reprocessing: bool + :ivar identity: The user-assigned managed identity used for connections to the enrichment + cache. If the connection string indicates an identity (ResourceId) and it's not specified, the + system-assigned managed identity is used. On updates to the indexer, if the identity is + unspecified, the value remains unchanged. If set to "none", the value of this property is + cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar id: A guid for the SearchIndexerCache. + :vartype id: str + """ + + storage_connection_string: Optional[str] = rest_field( + name="storageConnectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """The connection string to the storage account where the cache data will be persisted.""" + enable_reprocessing: Optional[bool] = rest_field( + name="enableReprocessing", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether incremental reprocessing is enabled.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for connections to the enrichment cache. If the + connection string indicates an identity (ResourceId) and it's not specified, the + system-assigned managed identity is used. On updates to the indexer, if the identity is + unspecified, the value remains unchanged. If set to \"none\", the value of this property is + cleared.""" + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A guid for the SearchIndexerCache.""" + + @overload + def __init__( + self, + *, + storage_connection_string: Optional[str] = None, + enable_reprocessing: Optional[bool] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataContainer(_Model): + """Represents information about the entity (such as Azure SQL table or CosmosDB collection) that + will be indexed. + + :ivar name: The name of the table or view (for Azure SQL data source) or collection (for + CosmosDB data source) that will be indexed. Required. + :vartype name: str + :ivar query: A query that is applied to this data container. The syntax and meaning of this + parameter is datasource-specific. Not supported by Azure SQL datasources. + :vartype query: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the table or view (for Azure SQL data source) or collection (for CosmosDB data + source) that will be indexed. Required.""" + query: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A query that is applied to this data container. The syntax and meaning of this parameter is + datasource-specific. Not supported by Azure SQL datasources.""" + + @overload + def __init__( + self, + *, + name: str, + query: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataIdentity(_Model): + """Abstract base type for data identities. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + SearchIndexerDataNoneIdentity, SearchIndexerDataUserAssignedIdentity + + :ivar odata_type: A URI fragment specifying the type of identity. Required. Default value is + None. + :vartype odata_type: str + """ + + __mapping__: dict[str, _Model] = {} + odata_type: str = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) + """A URI fragment specifying the type of identity. Required. Default value is None.""" + + @overload + def __init__( + self, + *, + odata_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataNoneIdentity( + SearchIndexerDataIdentity, discriminator="#Microsoft.Azure.Search.DataNoneIdentity" +): + """Clears the identity property of a datasource. + + :ivar odata_type: The discriminator for derived types. Required. Default value is + "#Microsoft.Azure.Search.DataNoneIdentity". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.DataNoneIdentity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator for derived types. Required. Default value is + \"#Microsoft.Azure.Search.DataNoneIdentity\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DataNoneIdentity" # type: ignore + + +class SearchIndexerDataSource(_Model): + """Represents a datasource definition, which can be used to configure an indexer. + + :ivar name: The name of the datasource. Required. + :vartype name: str + :ivar description: The description of the datasource. + :vartype description: str + :ivar type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", + "azureblob", "azuretable", "mysql", "adlsgen2", and "onelake". + :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType + :ivar sub_type: A specific type of the data source, in case the resource is capable of + different modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts. + :vartype sub_type: str + :ivar credentials: Credentials for the datasource. Required. + :vartype credentials: ~azure.search.documents.indexes.models.DataSourceCredentials + :ivar container: The data container for the datasource. Required. + :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer + :ivar identity: An explicit managed identity to use for this datasource. If not specified and + the connection string is a managed identity, the system-assigned managed identity is used. If + not specified, the value remains unchanged. If "none" is specified, the value of this property + is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar indexer_permission_options: Ingestion options with various types of permission data. + :vartype indexer_permission_options: list[str or + ~azure.search.documents.indexes.models.IndexerPermissionOption] + :ivar data_change_detection_policy: The data change detection policy for the datasource. + :vartype data_change_detection_policy: + ~azure.search.documents.indexes.models.DataChangeDetectionPolicy + :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource. + :vartype data_deletion_detection_policy: + ~azure.search.documents.indexes.models.DataDeletionDetectionPolicy + :ivar e_tag: The ETag of the data source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your datasource + definition when you want full assurance that no one, not even Microsoft, can decrypt your data + source definition. Once you have encrypted your data source definition, it will always remain + encrypted. The search service will ignore attempts to set this property to null. You can change + this property as needed if you want to rotate your encryption key; Your datasource definition + will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the datasource. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the datasource.""" + type: Union[str, "_models.SearchIndexerDataSourceType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of the datasource. Required. Known values are: \"azuresql\", \"cosmosdb\", + \"azureblob\", \"azuretable\", \"mysql\", \"adlsgen2\", and \"onelake\".""" + sub_type: Optional[str] = rest_field(name="subType", visibility=["read", "create", "update", "delete", "query"]) + """A specific type of the data source, in case the resource is capable of different modalities. + For example, 'MongoDb' for certain 'cosmosDb' accounts.""" + credentials: "_models.DataSourceCredentials" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Credentials for the datasource. Required.""" + container: "_models.SearchIndexerDataContainer" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The data container for the datasource. Required.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An explicit managed identity to use for this datasource. If not specified and the connection + string is a managed identity, the system-assigned managed identity is used. If not specified, + the value remains unchanged. If \"none\" is specified, the value of this property is cleared.""" + indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = rest_field( + name="indexerPermissionOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Ingestion options with various types of permission data.""" + data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = rest_field( + name="dataChangeDetectionPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The data change detection policy for the datasource.""" + data_deletion_detection_policy: Optional["_models.DataDeletionDetectionPolicy"] = rest_field( + name="dataDeletionDetectionPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The data deletion detection policy for the datasource.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the data source.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your datasource definition when you want + full assurance that no one, not even Microsoft, can decrypt your data source definition. Once + you have encrypted your data source definition, it will always remain encrypted. The search + service will ignore attempts to set this property to null. You can change this property as + needed if you want to rotate your encryption key; Your datasource definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019.""" + + @overload + def __init__( + self, + *, + name: str, + type: Union[str, "_models.SearchIndexerDataSourceType"], + credentials: "_models.DataSourceCredentials", + container: "_models.SearchIndexerDataContainer", + description: Optional[str] = None, + sub_type: Optional[str] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = None, + data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = None, + data_deletion_detection_policy: Optional["_models.DataDeletionDetectionPolicy"] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerDataUserAssignedIdentity( + SearchIndexerDataIdentity, discriminator="#Microsoft.Azure.Search.DataUserAssignedIdentity" +): + """Specifies the identity for a datasource to use. + + :ivar resource_id: The fully qualified Azure resource Id of a user assigned managed identity + typically in the form + "/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId" + that should have been assigned to the search service. Required. + :vartype resource_id: str + :ivar odata_type: A URI fragment specifying the type of identity. Required. Default value is + "#Microsoft.Azure.Search.DataUserAssignedIdentity". + :vartype odata_type: str + """ + + resource_id: str = rest_field( + name="userAssignedIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The fully qualified Azure resource Id of a user assigned managed identity typically in the form + \"/subscriptions/12345678-1234-1234-1234-1234567890ab/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId\" + that should have been assigned to the search service. Required.""" + odata_type: Literal["#Microsoft.Azure.Search.DataUserAssignedIdentity"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of identity. Required. Default value is + \"#Microsoft.Azure.Search.DataUserAssignedIdentity\".""" + + @overload + def __init__( + self, + *, + resource_id: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.DataUserAssignedIdentity" # type: ignore + + +class SearchIndexerError(_Model): + """Represents an item- or document-level indexing error. + + :ivar key: The key of the item for which indexing failed. + :vartype key: str + :ivar error_message: The message describing the error that occurred while processing the item. + Required. + :vartype error_message: str + :ivar status_code: The status code indicating why the indexing operation failed. Possible + values include: 400 for a malformed input document, 404 for document not found, 409 for a + version conflict, 422 when the index is temporarily unavailable, or 503 for when the service is + too busy. Required. + :vartype status_code: int + :ivar name: The name of the source at which the error originated. For example, this could refer + to a particular skill in the attached skillset. This may not be always available. + :vartype name: str + :ivar details: Additional, verbose details about the error to assist in debugging the indexer. + This may not be always available. + :vartype details: str + :ivar documentation_link: A link to a troubleshooting guide for these classes of errors. This + may not be always available. + :vartype documentation_link: str + """ + + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key of the item for which indexing failed.""" + error_message: str = rest_field(name="errorMessage", visibility=["read", "create", "update", "delete", "query"]) + """The message describing the error that occurred while processing the item. Required.""" + status_code: int = rest_field(name="statusCode", visibility=["read", "create", "update", "delete", "query"]) + """The status code indicating why the indexing operation failed. Possible values include: 400 for + a malformed input document, 404 for document not found, 409 for a version conflict, 422 when + the index is temporarily unavailable, or 503 for when the service is too busy. Required.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the source at which the error originated. For example, this could refer to a + particular skill in the attached skillset. This may not be always available.""" + details: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional, verbose details about the error to assist in debugging the indexer. This may not be + always available.""" + documentation_link: Optional[str] = rest_field( + name="documentationLink", visibility=["read", "create", "update", "delete", "query"] + ) + """A link to a troubleshooting guide for these classes of errors. This may not be always + available.""" + + @overload + def __init__( + self, + *, + error_message: str, + status_code: int, + key: Optional[str] = None, + name: Optional[str] = None, + details: Optional[str] = None, + documentation_link: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerIndexProjection(_Model): + """Definition of additional projections to secondary search indexes. + + :ivar selectors: A list of projections to be performed to secondary search indexes. Required. + :vartype selectors: + list[~azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector] + :ivar parameters: A dictionary of index projection-specific configuration properties. Each name + is the name of a specific property. Each value must be of a primitive type. + :vartype parameters: + ~azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters + """ + + selectors: list["_models.SearchIndexerIndexProjectionSelector"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of projections to be performed to secondary search indexes. Required.""" + parameters: Optional["_models.SearchIndexerIndexProjectionsParameters"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of index projection-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type.""" + + @overload + def __init__( + self, + *, + selectors: list["_models.SearchIndexerIndexProjectionSelector"], + parameters: Optional["_models.SearchIndexerIndexProjectionsParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerIndexProjectionSelector(_Model): + """Description for what data to store in the designated search index. + + :ivar target_index_name: Name of the search index to project to. Must have a key field with the + 'keyword' analyzer set. Required. + :vartype target_index_name: str + :ivar parent_key_field_name: Name of the field in the search index to map the parent document's + key value to. Must be a string field that is filterable and not the key field. Required. + :vartype parent_key_field_name: str + :ivar source_context: Source context for the projections. Represents the cardinality at which + the document will be split into multiple sub documents. Required. + :vartype source_context: str + :ivar mappings: Mappings for the projection, or which source should be mapped to which field in + the target index. Required. + :vartype mappings: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + """ + + target_index_name: str = rest_field( + name="targetIndexName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of the search index to project to. Must have a key field with the 'keyword' analyzer set. + Required.""" + parent_key_field_name: str = rest_field( + name="parentKeyFieldName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of the field in the search index to map the parent document's key value to. Must be a + string field that is filterable and not the key field. Required.""" + source_context: str = rest_field(name="sourceContext", visibility=["read", "create", "update", "delete", "query"]) + """Source context for the projections. Represents the cardinality at which the document will be + split into multiple sub documents. Required.""" + mappings: list["_models.InputFieldMappingEntry"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Mappings for the projection, or which source should be mapped to which field in the target + index. Required.""" + + @overload + def __init__( + self, + *, + target_index_name: str, + parent_key_field_name: str, + source_context: str, + mappings: list["_models.InputFieldMappingEntry"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerIndexProjectionsParameters(_Model): + """A dictionary of index projection-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type. + + :ivar projection_mode: Defines behavior of the index projections in relation to the rest of the + indexer. Known values are: "skipIndexingParentDocuments" and "includeIndexingParentDocuments". + :vartype projection_mode: str or ~azure.search.documents.indexes.models.IndexProjectionMode + """ + + projection_mode: Optional[Union[str, "_models.IndexProjectionMode"]] = rest_field( + name="projectionMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines behavior of the index projections in relation to the rest of the indexer. Known values + are: \"skipIndexingParentDocuments\" and \"includeIndexingParentDocuments\".""" + + @overload + def __init__( + self, + *, + projection_mode: Optional[Union[str, "_models.IndexProjectionMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStore(_Model): + """Definition of additional projections to azure blob, table, or files, of enriched data. + + :ivar storage_connection_string: The connection string to the storage account projections will + be stored in. Required. + :vartype storage_connection_string: str + :ivar projections: A list of additional projections to perform during indexing. Required. + :vartype projections: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection] + :ivar identity: The user-assigned managed identity used for connections to Azure Storage when + writing knowledge store projections. If the connection string indicates an identity + (ResourceId) and it's not specified, the system-assigned managed identity is used. On updates + to the indexer, if the identity is unspecified, the value remains unchanged. If set to "none", + the value of this property is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar parameters: A dictionary of knowledge store-specific configuration properties. Each name + is the name of a specific property. Each value must be of a primitive type. + :vartype parameters: + ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters + """ + + storage_connection_string: str = rest_field( + name="storageConnectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """The connection string to the storage account projections will be stored in. Required.""" + projections: list["_models.SearchIndexerKnowledgeStoreProjection"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of additional projections to perform during indexing. Required.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for connections to Azure Storage when writing knowledge + store projections. If the connection string indicates an identity (ResourceId) and it's not + specified, the system-assigned managed identity is used. On updates to the indexer, if the + identity is unspecified, the value remains unchanged. If set to \"none\", the value of this + property is cleared.""" + parameters: Optional["_models.SearchIndexerKnowledgeStoreParameters"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of knowledge store-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type.""" + + @overload + def __init__( + self, + *, + storage_connection_string: str, + projections: list["_models.SearchIndexerKnowledgeStoreProjection"], + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + parameters: Optional["_models.SearchIndexerKnowledgeStoreParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreProjectionSelector(_Model): # pylint: disable=name-too-long + """Abstract class to share properties between concrete selectors. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + """ + + reference_key_name: Optional[str] = rest_field( + name="referenceKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of reference key to different projection.""" + generated_key_name: Optional[str] = rest_field( + name="generatedKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of generated key to store projection under.""" + source: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Source data to project.""" + source_context: Optional[str] = rest_field( + name="sourceContext", visibility=["read", "create", "update", "delete", "query"] + ) + """Source context for complex projections.""" + inputs: Optional[list["_models.InputFieldMappingEntry"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Nested inputs for complex projections.""" + + @overload + def __init__( + self, + *, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreBlobProjectionSelector( + SearchIndexerKnowledgeStoreProjectionSelector +): # pylint: disable=name-too-long + """Abstract class to share properties between concrete selectors. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar storage_container: Blob container to store projections in. Required. + :vartype storage_container: str + """ + + storage_container: str = rest_field( + name="storageContainer", visibility=["read", "create", "update", "delete", "query"] + ) + """Blob container to store projections in. Required.""" + + @overload + def __init__( + self, + *, + storage_container: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreFileProjectionSelector( + SearchIndexerKnowledgeStoreBlobProjectionSelector +): # pylint: disable=name-too-long + """Projection definition for what data to store in Azure Files. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar storage_container: Blob container to store projections in. Required. + :vartype storage_container: str + """ + + @overload + def __init__( + self, + *, + storage_container: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreObjectProjectionSelector( + SearchIndexerKnowledgeStoreBlobProjectionSelector +): # pylint: disable=name-too-long + """Projection definition for what data to store in Azure Blob. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar storage_container: Blob container to store projections in. Required. + :vartype storage_container: str + """ + + @overload + def __init__( + self, + *, + storage_container: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreParameters(_Model): + """A dictionary of knowledge store-specific configuration properties. Each name is the name of a + specific property. Each value must be of a primitive type. + + :ivar synthesize_generated_key_name: Whether or not projections should synthesize a generated + key name if one isn't already present. + :vartype synthesize_generated_key_name: bool + """ + + synthesize_generated_key_name: Optional[bool] = rest_field( + name="synthesizeGeneratedKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Whether or not projections should synthesize a generated key name if one isn't already present.""" + + @overload + def __init__( + self, + *, + synthesize_generated_key_name: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreProjection(_Model): + """Container object for various projection selectors. + + :ivar tables: Projections to Azure Table storage. + :vartype tables: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector] + :ivar objects: Projections to Azure Blob storage. + :vartype objects: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector] + :ivar files: Projections to Azure File storage. + :vartype files: + list[~azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector] + """ + + tables: Optional[list["_models.SearchIndexerKnowledgeStoreTableProjectionSelector"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Projections to Azure Table storage.""" + objects: Optional[list["_models.SearchIndexerKnowledgeStoreObjectProjectionSelector"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Projections to Azure Blob storage.""" + files: Optional[list["_models.SearchIndexerKnowledgeStoreFileProjectionSelector"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Projections to Azure File storage.""" + + @overload + def __init__( + self, + *, + tables: Optional[list["_models.SearchIndexerKnowledgeStoreTableProjectionSelector"]] = None, + objects: Optional[list["_models.SearchIndexerKnowledgeStoreObjectProjectionSelector"]] = None, + files: Optional[list["_models.SearchIndexerKnowledgeStoreFileProjectionSelector"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerKnowledgeStoreTableProjectionSelector( + SearchIndexerKnowledgeStoreProjectionSelector +): # pylint: disable=name-too-long + """Description for what data to store in Azure Tables. + + :ivar reference_key_name: Name of reference key to different projection. + :vartype reference_key_name: str + :ivar generated_key_name: Name of generated key to store projection under. + :vartype generated_key_name: str + :ivar source: Source data to project. + :vartype source: str + :ivar source_context: Source context for complex projections. + :vartype source_context: str + :ivar inputs: Nested inputs for complex projections. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar table_name: Name of the Azure table to store projected data in. Required. + :vartype table_name: str + """ + + table_name: str = rest_field(name="tableName", visibility=["read", "create", "update", "delete", "query"]) + """Name of the Azure table to store projected data in. Required.""" + + @overload + def __init__( + self, + *, + table_name: str, + reference_key_name: Optional[str] = None, + generated_key_name: Optional[str] = None, + source: Optional[str] = None, + source_context: Optional[str] = None, + inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerLimits(_Model): + """Represents the limits that can be applied to an indexer. + + :ivar max_run_time: The maximum duration that the indexer is permitted to run for one + execution. + :vartype max_run_time: ~datetime.timedelta + :ivar max_document_extraction_size: The maximum size of a document, in bytes, which will be + considered valid for indexing. + :vartype max_document_extraction_size: int + :ivar max_document_content_characters_to_extract: The maximum number of characters that will be + extracted from a document picked up for indexing. + :vartype max_document_content_characters_to_extract: int + """ + + max_run_time: Optional[datetime.timedelta] = rest_field( + name="maxRunTime", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum duration that the indexer is permitted to run for one execution.""" + max_document_extraction_size: Optional[int] = rest_field( + name="maxDocumentExtractionSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum size of a document, in bytes, which will be considered valid for indexing.""" + max_document_content_characters_to_extract: Optional[int] = rest_field( + name="maxDocumentContentCharactersToExtract", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of characters that will be extracted from a document picked up for indexing.""" + + @overload + def __init__( + self, + *, + max_run_time: Optional[datetime.timedelta] = None, + max_document_extraction_size: Optional[int] = None, + max_document_content_characters_to_extract: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerSkillset(_Model): + """A list of skills. + + :ivar name: The name of the skillset. Required. + :vartype name: str + :ivar description: The description of the skillset. + :vartype description: str + :ivar skills: A list of skills in the skillset. Required. + :vartype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] + :ivar cognitive_services_account: Details about the Azure AI service to be used when running + skills. + :vartype cognitive_services_account: + ~azure.search.documents.indexes.models.CognitiveServicesAccount + :ivar knowledge_store: Definition of additional projections to Azure blob, table, or files, of + enriched data. + :vartype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore + :ivar index_projection: Definition of additional projections to secondary search index(es). + :vartype index_projection: ~azure.search.documents.indexes.models.SearchIndexerIndexProjection + :ivar e_tag: The ETag of the skillset. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your skillset + definition when you want full assurance that no one, not even Microsoft, can decrypt your + skillset definition. Once you have encrypted your skillset definition, it will always remain + encrypted. The search service will ignore attempts to set this property to null. You can change + this property as needed if you want to rotate your encryption key; Your skillset definition + will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the skillset. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the skillset.""" + skills: list["_models.SearchIndexerSkill"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of skills in the skillset. Required.""" + cognitive_services_account: Optional["_models.CognitiveServicesAccount"] = rest_field( + name="cognitiveServices", visibility=["read", "create", "update", "delete", "query"] + ) + """Details about the Azure AI service to be used when running skills.""" + knowledge_store: Optional["_models.SearchIndexerKnowledgeStore"] = rest_field( + name="knowledgeStore", visibility=["read", "create", "update", "delete", "query"] + ) + """Definition of additional projections to Azure blob, table, or files, of enriched data.""" + index_projection: Optional["_models.SearchIndexerIndexProjection"] = rest_field( + name="indexProjections", visibility=["read", "create", "update", "delete", "query"] + ) + """Definition of additional projections to secondary search index(es).""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the skillset.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your skillset definition when you want + full assurance that no one, not even Microsoft, can decrypt your skillset definition. Once you + have encrypted your skillset definition, it will always remain encrypted. The search service + will ignore attempts to set this property to null. You can change this property as needed if + you want to rotate your encryption key; Your skillset definition will be unaffected. Encryption + with customer-managed keys is not available for free search services, and is only available for + paid services created on or after January 1, 2019.""" + + @overload + def __init__( + self, + *, + name: str, + skills: list["_models.SearchIndexerSkill"], + description: Optional[str] = None, + cognitive_services_account: Optional["_models.CognitiveServicesAccount"] = None, + knowledge_store: Optional["_models.SearchIndexerKnowledgeStore"] = None, + index_projection: Optional["_models.SearchIndexerIndexProjection"] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerStatus(_Model): + """Represents the current status and execution history of an indexer. + + :ivar name: The name of the indexer. Required. + :vartype name: str + :ivar status: Overall indexer status. Required. Known values are: "unknown", "error", and + "running". + :vartype status: str or ~azure.search.documents.indexes.models.IndexerStatus + :ivar last_result: The result of the most recent or an in-progress indexer execution. + :vartype last_result: ~azure.search.documents.indexes.models.IndexerExecutionResult + :ivar execution_history: History of the recent indexer executions, sorted in reverse + chronological order. Required. + :vartype execution_history: list[~azure.search.documents.indexes.models.IndexerExecutionResult] + :ivar limits: The execution limits for the indexer. Required. + :vartype limits: ~azure.search.documents.indexes.models.SearchIndexerLimits + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the indexer. Required.""" + status: Union[str, "_models.IndexerStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Overall indexer status. Required. Known values are: \"unknown\", \"error\", and \"running\".""" + last_result: Optional["_models.IndexerExecutionResult"] = rest_field( + name="lastResult", visibility=["read", "create", "update", "delete", "query"] + ) + """The result of the most recent or an in-progress indexer execution.""" + execution_history: list["_models.IndexerExecutionResult"] = rest_field( + name="executionHistory", visibility=["read", "create", "update", "delete", "query"] + ) + """History of the recent indexer executions, sorted in reverse chronological order. Required.""" + limits: "_models.SearchIndexerLimits" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The execution limits for the indexer. Required.""" + + @overload + def __init__( + self, + *, + name: str, + status: Union[str, "_models.IndexerStatus"], + execution_history: list["_models.IndexerExecutionResult"], + limits: "_models.SearchIndexerLimits", + last_result: Optional["_models.IndexerExecutionResult"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexerWarning(_Model): + """Represents an item-level warning. + + :ivar key: The key of the item which generated a warning. + :vartype key: str + :ivar message: The message describing the warning that occurred while processing the item. + Required. + :vartype message: str + :ivar name: The name of the source at which the warning originated. For example, this could + refer to a particular skill in the attached skillset. This may not be always available. + :vartype name: str + :ivar details: Additional, verbose details about the warning to assist in debugging the + indexer. This may not be always available. + :vartype details: str + :ivar documentation_link: A link to a troubleshooting guide for these classes of warnings. This + may not be always available. + :vartype documentation_link: str + """ + + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key of the item which generated a warning.""" + message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The message describing the warning that occurred while processing the item. Required.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the source at which the warning originated. For example, this could refer to a + particular skill in the attached skillset. This may not be always available.""" + details: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional, verbose details about the warning to assist in debugging the indexer. This may not + be always available.""" + documentation_link: Optional[str] = rest_field( + name="documentationLink", visibility=["read", "create", "update", "delete", "query"] + ) + """A link to a troubleshooting guide for these classes of warnings. This may not be always + available.""" + + @overload + def __init__( + self, + *, + message: str, + key: Optional[str] = None, + name: Optional[str] = None, + details: Optional[str] = None, + documentation_link: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchIndexKnowledgeSource(KnowledgeSource, discriminator="searchIndex"): + """Knowledge Source targeting a search index. + + :ivar name: The name of the knowledge source. Required. + :vartype name: str + :ivar description: Optional user-defined description. + :vartype description: str + :ivar e_tag: The ETag of the agent. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar kind: Required. A knowledge source that reads data from a Search Index. + :vartype kind: str or ~azure.search.documents.indexes.models.SEARCH_INDEX + :ivar search_index_parameters: The parameters for the knowledge source. Required. + :vartype search_index_parameters: + ~azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters + """ + + kind: Literal[KnowledgeSourceKind.SEARCH_INDEX] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. A knowledge source that reads data from a Search Index.""" + search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters" = rest_field( + name="searchIndexParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The parameters for the knowledge source. Required.""" + + @overload + def __init__( + self, + *, + search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters", + description: Optional[str] = None, + e_tag: Optional[str] = None, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.SEARCH_INDEX # type: ignore + + +class SearchIndexKnowledgeSourceParameters(_Model): + """Parameters for search index knowledge source. + + :ivar search_index_name: The name of the Search index. Required. + :vartype search_index_name: str + :ivar source_data_select: Used to request additional fields for referenced source data. + :vartype source_data_select: str + """ + + search_index_name: str = rest_field( + name="searchIndexName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the Search index. Required.""" + source_data_select: Optional[str] = rest_field( + name="sourceDataSelect", visibility=["read", "create", "update", "delete", "query"] + ) + """Used to request additional fields for referenced source data.""" + + @overload + def __init__( + self, + *, + search_index_name: str, + source_data_select: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchResourceEncryptionKey(_Model): + """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be + used to encrypt or decrypt data-at-rest, such as indexes and synonym maps. + + :ivar key_name: The name of your Azure Key Vault key to be used to encrypt your data at rest. + Required. + :vartype key_name: str + :ivar key_version: The version of your Azure Key Vault key to be used to encrypt your data at + rest. + :vartype key_version: str + :ivar vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that contains + the key to be used to encrypt your data at rest. An example URI might be + ``https://my-keyvault-name.vault.azure.net``. Required. + :vartype vault_uri: str + :ivar access_credentials: Optional Azure Active Directory credentials used for accessing your + Azure Key Vault. Not required if using managed identity instead. + :vartype access_credentials: + ~azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials + :ivar identity: An explicit managed identity to use for this encryption key. If not specified + and the access credentials property is null, the system-assigned managed identity is used. On + update to the resource, if the explicit identity is unspecified, it remains unchanged. If + "none" is specified, the value of this property is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + """ + + key_name: str = rest_field(name="keyVaultKeyName", visibility=["read", "create", "update", "delete", "query"]) + """The name of your Azure Key Vault key to be used to encrypt your data at rest. Required.""" + key_version: Optional[str] = rest_field( + name="keyVaultKeyVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of your Azure Key Vault key to be used to encrypt your data at rest.""" + vault_uri: str = rest_field(name="keyVaultUri", visibility=["read", "create", "update", "delete", "query"]) + """The URI of your Azure Key Vault, also referred to as DNS name, that contains the key to be used + to encrypt your data at rest. An example URI might be + ``https://my-keyvault-name.vault.azure.net``. Required.""" + access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = rest_field( + name="accessCredentials", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional Azure Active Directory credentials used for accessing your Azure Key Vault. Not + required if using managed identity instead.""" + identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """An explicit managed identity to use for this encryption key. If not specified and the access + credentials property is null, the system-assigned managed identity is used. On update to the + resource, if the explicit identity is unspecified, it remains unchanged. If \"none\" is + specified, the value of this property is cleared.""" + + @overload + def __init__( + self, + *, + key_name: str, + vault_uri: str, + key_version: Optional[str] = None, + access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = None, + identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchServiceCounters(_Model): + """Represents service-level resource counters and quotas. + + :ivar alias_counter: Total number of aliases. Required. + :vartype alias_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar document_counter: Total number of documents across all indexes in the service. Required. + :vartype document_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar index_counter: Total number of indexes. Required. + :vartype index_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar indexer_counter: Total number of indexers. Required. + :vartype indexer_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar data_source_counter: Total number of data sources. Required. + :vartype data_source_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar storage_size_counter: Total size of used storage in bytes. Required. + :vartype storage_size_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar synonym_map_counter: Total number of synonym maps. Required. + :vartype synonym_map_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar skillset_counter: Total number of skillsets. Required. + :vartype skillset_counter: ~azure.search.documents.indexes.models.ResourceCounter + :ivar vector_index_size_counter: Total memory consumption of all vector indexes within the + service, in bytes. Required. + :vartype vector_index_size_counter: ~azure.search.documents.indexes.models.ResourceCounter + """ + + alias_counter: "_models.ResourceCounter" = rest_field( + name="aliasesCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of aliases. Required.""" + document_counter: "_models.ResourceCounter" = rest_field( + name="documentCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of documents across all indexes in the service. Required.""" + index_counter: "_models.ResourceCounter" = rest_field( + name="indexesCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of indexes. Required.""" + indexer_counter: "_models.ResourceCounter" = rest_field( + name="indexersCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of indexers. Required.""" + data_source_counter: "_models.ResourceCounter" = rest_field( + name="dataSourcesCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of data sources. Required.""" + storage_size_counter: "_models.ResourceCounter" = rest_field( + name="storageSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Total size of used storage in bytes. Required.""" + synonym_map_counter: "_models.ResourceCounter" = rest_field( + name="synonymMaps", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of synonym maps. Required.""" + skillset_counter: "_models.ResourceCounter" = rest_field( + name="skillsetCount", visibility=["read", "create", "update", "delete", "query"] + ) + """Total number of skillsets. Required.""" + vector_index_size_counter: "_models.ResourceCounter" = rest_field( + name="vectorIndexSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Total memory consumption of all vector indexes within the service, in bytes. Required.""" + + @overload + def __init__( + self, + *, + alias_counter: "_models.ResourceCounter", + document_counter: "_models.ResourceCounter", + index_counter: "_models.ResourceCounter", + indexer_counter: "_models.ResourceCounter", + data_source_counter: "_models.ResourceCounter", + storage_size_counter: "_models.ResourceCounter", + synonym_map_counter: "_models.ResourceCounter", + skillset_counter: "_models.ResourceCounter", + vector_index_size_counter: "_models.ResourceCounter", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchServiceLimits(_Model): + """Represents various service level limits. + + :ivar max_fields_per_index: The maximum allowed fields per index. + :vartype max_fields_per_index: int + :ivar max_field_nesting_depth_per_index: The maximum depth which you can nest sub-fields in an + index, including the top-level complex field. For example, a/b/c has a nesting depth of 3. + :vartype max_field_nesting_depth_per_index: int + :ivar max_complex_collection_fields_per_index: The maximum number of fields of type + Collection(Edm.ComplexType) allowed in an index. + :vartype max_complex_collection_fields_per_index: int + :ivar max_complex_objects_in_collections_per_document: The maximum number of objects in complex + collections allowed per document. + :vartype max_complex_objects_in_collections_per_document: int + :ivar max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per index. + :vartype max_storage_per_index_in_bytes: int + """ + + max_fields_per_index: Optional[int] = rest_field( + name="maxFieldsPerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum allowed fields per index.""" + max_field_nesting_depth_per_index: Optional[int] = rest_field( + name="maxFieldNestingDepthPerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum depth which you can nest sub-fields in an index, including the top-level complex + field. For example, a/b/c has a nesting depth of 3.""" + max_complex_collection_fields_per_index: Optional[int] = rest_field( + name="maxComplexCollectionFieldsPerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of fields of type Collection(Edm.ComplexType) allowed in an index.""" + max_complex_objects_in_collections_per_document: Optional[int] = rest_field( + name="maxComplexObjectsInCollectionsPerDocument", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of objects in complex collections allowed per document.""" + max_storage_per_index_in_bytes: Optional[int] = rest_field( + name="maxStoragePerIndex", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum amount of storage in bytes allowed per index.""" + + @overload + def __init__( + self, + *, + max_fields_per_index: Optional[int] = None, + max_field_nesting_depth_per_index: Optional[int] = None, + max_complex_collection_fields_per_index: Optional[int] = None, + max_complex_objects_in_collections_per_document: Optional[int] = None, + max_storage_per_index_in_bytes: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchServiceStatistics(_Model): + """Response from a get service statistics request. If successful, it includes service level + counters and limits. + + :ivar counters: Service level resource counters. Required. + :vartype counters: ~azure.search.documents.indexes.models.SearchServiceCounters + :ivar limits: Service level general limits. Required. + :vartype limits: ~azure.search.documents.indexes.models.SearchServiceLimits + """ + + counters: "_models.SearchServiceCounters" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Service level resource counters. Required.""" + limits: "_models.SearchServiceLimits" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Service level general limits. Required.""" + + @overload + def __init__( + self, + *, + counters: "_models.SearchServiceCounters", + limits: "_models.SearchServiceLimits", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchSuggester(_Model): + """Defines how the Suggest API should apply to a group of fields in the index. + + :ivar name: The name of the suggester. Required. + :vartype name: str + :ivar search_mode: A value indicating the capabilities of the suggester. Required. Default + value is "analyzingInfixMatching". + :vartype search_mode: str + :ivar source_fields: The list of field names to which the suggester applies. Each field must be + searchable. Required. + :vartype source_fields: list[str] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the suggester. Required.""" + search_mode: Literal["analyzingInfixMatching"] = rest_field( + name="searchMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating the capabilities of the suggester. Required. Default value is + \"analyzingInfixMatching\".""" + source_fields: list[str] = rest_field( + name="sourceFields", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of field names to which the suggester applies. Each field must be searchable. + Required.""" + + @overload + def __init__( + self, + *, + name: str, + source_fields: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.search_mode: Literal["analyzingInfixMatching"] = "analyzingInfixMatching" + + +class SemanticConfiguration(_Model): + """Defines a specific configuration to be used in the context of semantic capabilities. + + :ivar name: The name of the semantic configuration. Required. + :vartype name: str + :ivar prioritized_fields: Describes the title, content, and keyword fields to be used for + semantic ranking, captions, highlights, and answers. At least one of the three sub properties + (titleField, prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required. + :vartype prioritized_fields: ~azure.search.documents.indexes.models.SemanticPrioritizedFields + :ivar ranking_order: Specifies the score type to be used for the sort order of the search + results. Known values are: "BoostedRerankerScore" and "RerankerScore". + :vartype ranking_order: str or ~azure.search.documents.indexes.models.RankingOrder + :ivar flighting_opt_in: Determines which semantic or query rewrite models to use during model + flighting/upgrades. + :vartype flighting_opt_in: bool + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the semantic configuration. Required.""" + prioritized_fields: "_models.SemanticPrioritizedFields" = rest_field( + name="prioritizedFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Describes the title, content, and keyword fields to be used for semantic ranking, captions, + highlights, and answers. At least one of the three sub properties (titleField, + prioritizedKeywordsFields and prioritizedContentFields) need to be set. Required.""" + ranking_order: Optional[Union[str, "_models.RankingOrder"]] = rest_field( + name="rankingOrder", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the score type to be used for the sort order of the search results. Known values are: + \"BoostedRerankerScore\" and \"RerankerScore\".""" + flighting_opt_in: Optional[bool] = rest_field( + name="flightingOptIn", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines which semantic or query rewrite models to use during model flighting/upgrades.""" + + @overload + def __init__( + self, + *, + name: str, + prioritized_fields: "_models.SemanticPrioritizedFields", + ranking_order: Optional[Union[str, "_models.RankingOrder"]] = None, + flighting_opt_in: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SemanticField(_Model): + """A field that is used as part of the semantic configuration. + + :ivar field_name: File name. Required. + :vartype field_name: str + """ + + field_name: str = rest_field(name="fieldName", visibility=["read", "create", "update", "delete", "query"]) + """File name. Required.""" + + @overload + def __init__( + self, + *, + field_name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SemanticPrioritizedFields(_Model): + """Describes the title, content, and keywords fields to be used for semantic ranking, captions, + highlights, and answers. + + :ivar title_field: Defines the title field to be used for semantic ranking, captions, + highlights, and answers. If you don't have a title field in your index, leave this blank. + :vartype title_field: ~azure.search.documents.indexes.models.SemanticField + :ivar content_fields: Defines the content fields to be used for semantic ranking, captions, + highlights, and answers. For the best result, the selected fields should contain text in + natural language form. The order of the fields in the array represents their priority. Fields + with lower priority may get truncated if the content is long. + :vartype content_fields: list[~azure.search.documents.indexes.models.SemanticField] + :ivar keywords_fields: Defines the keyword fields to be used for semantic ranking, captions, + highlights, and answers. For the best result, the selected fields should contain a list of + keywords. The order of the fields in the array represents their priority. Fields with lower + priority may get truncated if the content is long. + :vartype keywords_fields: list[~azure.search.documents.indexes.models.SemanticField] + """ + + title_field: Optional["_models.SemanticField"] = rest_field( + name="titleField", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the title field to be used for semantic ranking, captions, highlights, and answers. If + you don't have a title field in your index, leave this blank.""" + content_fields: Optional[list["_models.SemanticField"]] = rest_field( + name="prioritizedContentFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the content fields to be used for semantic ranking, captions, highlights, and answers. + For the best result, the selected fields should contain text in natural language form. The + order of the fields in the array represents their priority. Fields with lower priority may get + truncated if the content is long.""" + keywords_fields: Optional[list["_models.SemanticField"]] = rest_field( + name="prioritizedKeywordsFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the keyword fields to be used for semantic ranking, captions, highlights, and answers. + For the best result, the selected fields should contain a list of keywords. The order of the + fields in the array represents their priority. Fields with lower priority may get truncated if + the content is long.""" + + @overload + def __init__( + self, + *, + title_field: Optional["_models.SemanticField"] = None, + content_fields: Optional[list["_models.SemanticField"]] = None, + keywords_fields: Optional[list["_models.SemanticField"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SemanticSearch(_Model): + """Defines parameters for a search index that influence semantic capabilities. + + :ivar default_configuration_name: Allows you to set the name of a default semantic + configuration in your index, making it optional to pass it on as a query parameter every time. + :vartype default_configuration_name: str + :ivar configurations: The semantic configurations for the index. + :vartype configurations: list[~azure.search.documents.indexes.models.SemanticConfiguration] + """ + + default_configuration_name: Optional[str] = rest_field( + name="defaultConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows you to set the name of a default semantic configuration in your index, making it + optional to pass it on as a query parameter every time.""" + configurations: Optional[list["_models.SemanticConfiguration"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The semantic configurations for the index.""" + + @overload + def __init__( + self, + *, + default_configuration_name: Optional[str] = None, + configurations: Optional[list["_models.SemanticConfiguration"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SentimentSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.SentimentSkill"): + """This skill is deprecated. Use the V3.SentimentSkill instead. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", "ru", + "es", "sv", and "tr". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.SentimentSkillLanguage + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.SentimentSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.SentimentSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"da\", + \"nl\", \"en\", \"fi\", \"fr\", \"de\", \"el\", \"it\", \"no\", \"pl\", \"pt-PT\", \"ru\", + \"es\", \"sv\", and \"tr\".""" + odata_type: Literal["#Microsoft.Skills.Text.SentimentSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.SentimentSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.SentimentSkillLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.SentimentSkill" # type: ignore + + +class SentimentSkillV3(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.V3.SentimentSkill"): + """Using the Text Analytics API, evaluates unstructured text and for each record, provides + sentiment labels (such as "negative", "neutral" and "positive") based on the highest confidence + score found by the service at a sentence and document-level. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + :vartype default_language_code: str + :ivar include_opinion_mining: If set to true, the skill output will include information from + Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated + assessment (adjective) in the text. Default is false. + :vartype include_opinion_mining: bool + :ivar model_version: The version of the model to use when calling the Text Analytics service. + It will default to the latest available when not specified. We recommend you do not specify + this value unless absolutely necessary. + :vartype model_version: str + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.V3.SentimentSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[str] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``.""" + include_opinion_mining: Optional[bool] = rest_field( + name="includeOpinionMining", visibility=["read", "create", "update", "delete", "query"] + ) + """If set to true, the skill output will include information from Text Analytics for opinion + mining, namely targets (nouns or verbs) and their associated assessment (adjective) in the + text. Default is false.""" + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the model to use when calling the Text Analytics service. It will default to the + latest available when not specified. We recommend you do not specify this value unless + absolutely necessary.""" + odata_type: Literal["#Microsoft.Skills.Text.V3.SentimentSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.V3.SentimentSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[str] = None, + include_opinion_mining: Optional[bool] = None, + model_version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.V3.SentimentSkill" # type: ignore + + +class ShaperSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.ShaperSkill"): + """A skill for reshaping the outputs. It creates a complex type to support composite fields (also + known as multipart fields). + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.ShaperSkill". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Skills.Util.ShaperSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.ShaperSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.ShaperSkill" # type: ignore + + +class ShingleTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.ShingleTokenFilter"): + """Creates combinations of tokens as a single token. This token filter is implemented using Apache + Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar max_shingle_size: The maximum shingle size. Default and minimum value is 2. + :vartype max_shingle_size: int + :ivar min_shingle_size: The minimum shingle size. Default and minimum value is 2. Must be less + than the value of maxShingleSize. + :vartype min_shingle_size: int + :ivar output_unigrams: A value indicating whether the output stream will contain the input + tokens (unigrams) as well as shingles. Default is true. + :vartype output_unigrams: bool + :ivar output_unigrams_if_no_shingles: A value indicating whether to output unigrams for those + times when no shingles are available. This property takes precedence when outputUnigrams is set + to false. Default is false. + :vartype output_unigrams_if_no_shingles: bool + :ivar token_separator: The string to use when joining adjacent tokens to form a shingle. + Default is a single space (" "). + :vartype token_separator: str + :ivar filter_token: The string to insert for each position at which there is no token. Default + is an underscore ("_"). + :vartype filter_token: str + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.ShingleTokenFilter". + :vartype odata_type: str + """ + + max_shingle_size: Optional[int] = rest_field( + name="maxShingleSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum shingle size. Default and minimum value is 2.""" + min_shingle_size: Optional[int] = rest_field( + name="minShingleSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The minimum shingle size. Default and minimum value is 2. Must be less than the value of + maxShingleSize.""" + output_unigrams: Optional[bool] = rest_field( + name="outputUnigrams", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the output stream will contain the input tokens (unigrams) as well + as shingles. Default is true.""" + output_unigrams_if_no_shingles: Optional[bool] = rest_field( + name="outputUnigramsIfNoShingles", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to output unigrams for those times when no shingles are available. + This property takes precedence when outputUnigrams is set to false. Default is false.""" + token_separator: Optional[str] = rest_field( + name="tokenSeparator", visibility=["read", "create", "update", "delete", "query"] + ) + """The string to use when joining adjacent tokens to form a shingle. Default is a single space (\" + \").""" + filter_token: Optional[str] = rest_field( + name="filterToken", visibility=["read", "create", "update", "delete", "query"] + ) + """The string to insert for each position at which there is no token. Default is an underscore + (\"_\").""" + odata_type: Literal["#Microsoft.Azure.Search.ShingleTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.ShingleTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + max_shingle_size: Optional[int] = None, + min_shingle_size: Optional[int] = None, + output_unigrams: Optional[bool] = None, + output_unigrams_if_no_shingles: Optional[bool] = None, + token_separator: Optional[str] = None, + filter_token: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.ShingleTokenFilter" # type: ignore + + +class SkillNames(_Model): + """The type of the skill names. + + :ivar skill_names: the names of skills to be reset. + :vartype skill_names: list[str] + """ + + skill_names: Optional[list[str]] = rest_field( + name="skillNames", visibility=["read", "create", "update", "delete", "query"] + ) + """the names of skills to be reset.""" + + @overload + def __init__( + self, + *, + skill_names: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SnowballTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.SnowballTokenFilter"): + """A filter that stems words using a Snowball-generated stemmer. This token filter is implemented + using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar language: The language to use. Required. Known values are: "armenian", "basque", + "catalan", "danish", "dutch", "english", "finnish", "french", "german", "german2", "hungarian", + "italian", "kp", "lovins", "norwegian", "porter", "portuguese", "romanian", "russian", + "spanish", "swedish", and "turkish". + :vartype language: str or ~azure.search.documents.indexes.models.SnowballTokenFilterLanguage + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.SnowballTokenFilter". + :vartype odata_type: str + """ + + language: Union[str, "_models.SnowballTokenFilterLanguage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. Required. Known values are: \"armenian\", \"basque\", \"catalan\", + \"danish\", \"dutch\", \"english\", \"finnish\", \"french\", \"german\", \"german2\", + \"hungarian\", \"italian\", \"kp\", \"lovins\", \"norwegian\", \"porter\", \"portuguese\", + \"romanian\", \"russian\", \"spanish\", \"swedish\", and \"turkish\".""" + odata_type: Literal["#Microsoft.Azure.Search.SnowballTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.SnowballTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + language: Union[str, "_models.SnowballTokenFilterLanguage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SnowballTokenFilter" # type: ignore + + +class SoftDeleteColumnDeletionDetectionPolicy( + DataDeletionDetectionPolicy, discriminator="#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy" +): + """Defines a data deletion detection policy that implements a soft-deletion strategy. It + determines whether an item should be deleted based on the value of a designated 'soft delete' + column. + + :ivar soft_delete_column_name: The name of the column to use for soft-deletion detection. + :vartype soft_delete_column_name: str + :ivar soft_delete_marker_value: The marker value that identifies an item as deleted. + :vartype soft_delete_marker_value: str + :ivar odata_type: A URI fragment specifying the type of data deletion detection policy. + Required. Default value is "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy". + :vartype odata_type: str + """ + + soft_delete_column_name: Optional[str] = rest_field( + name="softDeleteColumnName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the column to use for soft-deletion detection.""" + soft_delete_marker_value: Optional[str] = rest_field( + name="softDeleteMarkerValue", visibility=["read", "create", "update", "delete", "query"] + ) + """The marker value that identifies an item as deleted.""" + odata_type: Literal["#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data deletion detection policy. Required. Default value + is \"#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy\".""" + + @overload + def __init__( + self, + *, + soft_delete_column_name: Optional[str] = None, + soft_delete_marker_value: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy" # type: ignore + + +class SplitSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.SplitSkill"): + """A skill to split a string into chunks of text. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_language_code: A value indicating which language code to use. Default is ``en``. + Known values are: "am", "bs", "cs", "da", "de", "en", "es", "et", "fi", "fr", "he", "hi", "hr", + "hu", "id", "is", "it", "ja", "ko", "lv", "nb", "nl", "pl", "pt", "pt-br", "ru", "sk", "sl", + "sr", "sv", "tr", "ur", and "zh". + :vartype default_language_code: str or + ~azure.search.documents.indexes.models.SplitSkillLanguage + :ivar text_split_mode: A value indicating which split mode to perform. Known values are: + "pages" and "sentences". + :vartype text_split_mode: str or ~azure.search.documents.indexes.models.TextSplitMode + :ivar maximum_page_length: The desired maximum page length. Default is 10000. + :vartype maximum_page_length: int + :ivar page_overlap_length: Only applicable when textSplitMode is set to 'pages'. If specified, + n+1th chunk will start with this number of characters/tokens from the end of the nth chunk. + :vartype page_overlap_length: int + :ivar maximum_pages_to_take: Only applicable when textSplitMode is set to 'pages'. If + specified, the SplitSkill will discontinue splitting after processing the first + 'maximumPagesToTake' pages, in order to improve performance when only a few initial pages are + needed from each document. + :vartype maximum_pages_to_take: int + :ivar unit: Only applies if textSplitMode is set to pages. There are two possible values. The + choice of the values will decide the length (maximumPageLength and pageOverlapLength) + measurement. The default is 'characters', which means the length will be measured by character. + Known values are: "characters" and "azureOpenAITokens". + :vartype unit: str or ~azure.search.documents.indexes.models.SplitSkillUnit + :ivar azure_open_ai_tokenizer_parameters: Only applies if the unit is set to azureOpenAITokens. + If specified, the splitSkill will use these parameters when performing the tokenization. The + parameters are a valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. + :vartype azure_open_ai_tokenizer_parameters: + ~azure.search.documents.indexes.models.AzureOpenAITokenizerParameters + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.SplitSkill". + :vartype odata_type: str + """ + + default_language_code: Optional[Union[str, "_models.SplitSkillLanguage"]] = rest_field( + name="defaultLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which language code to use. Default is ``en``. Known values are: \"am\", + \"bs\", \"cs\", \"da\", \"de\", \"en\", \"es\", \"et\", \"fi\", \"fr\", \"he\", \"hi\", \"hr\", + \"hu\", \"id\", \"is\", \"it\", \"ja\", \"ko\", \"lv\", \"nb\", \"nl\", \"pl\", \"pt\", + \"pt-br\", \"ru\", \"sk\", \"sl\", \"sr\", \"sv\", \"tr\", \"ur\", and \"zh\".""" + text_split_mode: Optional[Union[str, "_models.TextSplitMode"]] = rest_field( + name="textSplitMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating which split mode to perform. Known values are: \"pages\" and \"sentences\".""" + maximum_page_length: Optional[int] = rest_field( + name="maximumPageLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The desired maximum page length. Default is 10000.""" + page_overlap_length: Optional[int] = rest_field( + name="pageOverlapLength", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applicable when textSplitMode is set to 'pages'. If specified, n+1th chunk will start with + this number of characters/tokens from the end of the nth chunk.""" + maximum_pages_to_take: Optional[int] = rest_field( + name="maximumPagesToTake", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applicable when textSplitMode is set to 'pages'. If specified, the SplitSkill will + discontinue splitting after processing the first 'maximumPagesToTake' pages, in order to + improve performance when only a few initial pages are needed from each document.""" + unit: Optional[Union[str, "_models.SplitSkillUnit"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Only applies if textSplitMode is set to pages. There are two possible values. The choice of the + values will decide the length (maximumPageLength and pageOverlapLength) measurement. The + default is 'characters', which means the length will be measured by character. Known values + are: \"characters\" and \"azureOpenAITokens\".""" + azure_open_ai_tokenizer_parameters: Optional["_models.AzureOpenAITokenizerParameters"] = rest_field( + name="azureOpenAITokenizerParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Only applies if the unit is set to azureOpenAITokens. If specified, the splitSkill will use + these parameters when performing the tokenization. The parameters are a valid + 'encoderModelName' and an optional 'allowedSpecialTokens' property.""" + odata_type: Literal["#Microsoft.Skills.Text.SplitSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.SplitSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_language_code: Optional[Union[str, "_models.SplitSkillLanguage"]] = None, + text_split_mode: Optional[Union[str, "_models.TextSplitMode"]] = None, + maximum_page_length: Optional[int] = None, + page_overlap_length: Optional[int] = None, + maximum_pages_to_take: Optional[int] = None, + unit: Optional[Union[str, "_models.SplitSkillUnit"]] = None, + azure_open_ai_tokenizer_parameters: Optional["_models.AzureOpenAITokenizerParameters"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.SplitSkill" # type: ignore + + +class SqlIntegratedChangeTrackingPolicy( + DataChangeDetectionPolicy, discriminator="#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy" +): + """Defines a data change detection policy that captures changes using the Integrated Change + Tracking feature of Azure SQL Database. + + :ivar odata_type: A URI fragment specifying the type of data change detection policy. Required. + Default value is "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy". + :vartype odata_type: str + """ + + odata_type: Literal["#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of data change detection policy. Required. Default value is + \"#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy" # type: ignore + + +class StemmerOverrideTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StemmerOverrideTokenFilter"): + """Provides the ability to override other stemming filters with custom dictionary-based stemming. + Any dictionary-stemmed terms will be marked as keywords so that they will not be stemmed with + stemmers down the chain. Must be placed before any stemming filters. This token filter is + implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar rules: A list of stemming rules in the following format: "word => stem", for example: + "ran => run". Required. + :vartype rules: list[str] + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.StemmerOverrideTokenFilter". + :vartype odata_type: str + """ + + rules: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stemming rules in the following format: \"word => stem\", for example: \"ran => + run\". Required.""" + odata_type: Literal["#Microsoft.Azure.Search.StemmerOverrideTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.StemmerOverrideTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + rules: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StemmerOverrideTokenFilter" # type: ignore + + +class StemmerTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StemmerTokenFilter"): + """Language specific stemming filter. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar language: The language to use. Required. Known values are: "arabic", "armenian", + "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "dutchKp", + "english", "lightEnglish", "minimalEnglish", "possessiveEnglish", "porter2", "lovins", + "finnish", "lightFinnish", "french", "lightFrench", "minimalFrench", "galician", + "minimalGalician", "german", "german2", "lightGerman", "minimalGerman", "greek", "hindi", + "hungarian", "lightHungarian", "indonesian", "irish", "italian", "lightItalian", "sorani", + "latvian", "norwegian", "lightNorwegian", "minimalNorwegian", "lightNynorsk", "minimalNynorsk", + "portuguese", "lightPortuguese", "minimalPortuguese", "portugueseRslp", "romanian", "russian", + "lightRussian", "spanish", "lightSpanish", "swedish", "lightSwedish", and "turkish". + :vartype language: str or ~azure.search.documents.indexes.models.StemmerTokenFilterLanguage + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.StemmerTokenFilter". + :vartype odata_type: str + """ + + language: Union[str, "_models.StemmerTokenFilterLanguage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The language to use. Required. Known values are: \"arabic\", \"armenian\", \"basque\", + \"brazilian\", \"bulgarian\", \"catalan\", \"czech\", \"danish\", \"dutch\", \"dutchKp\", + \"english\", \"lightEnglish\", \"minimalEnglish\", \"possessiveEnglish\", \"porter2\", + \"lovins\", \"finnish\", \"lightFinnish\", \"french\", \"lightFrench\", \"minimalFrench\", + \"galician\", \"minimalGalician\", \"german\", \"german2\", \"lightGerman\", \"minimalGerman\", + \"greek\", \"hindi\", \"hungarian\", \"lightHungarian\", \"indonesian\", \"irish\", + \"italian\", \"lightItalian\", \"sorani\", \"latvian\", \"norwegian\", \"lightNorwegian\", + \"minimalNorwegian\", \"lightNynorsk\", \"minimalNynorsk\", \"portuguese\", + \"lightPortuguese\", \"minimalPortuguese\", \"portugueseRslp\", \"romanian\", \"russian\", + \"lightRussian\", \"spanish\", \"lightSpanish\", \"swedish\", \"lightSwedish\", and + \"turkish\".""" + odata_type: Literal["#Microsoft.Azure.Search.StemmerTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.StemmerTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + language: Union[str, "_models.StemmerTokenFilterLanguage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StemmerTokenFilter" # type: ignore + + +class StopAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StopAnalyzer"): + """Divides text at non-letters; Applies the lowercase and stopword token filters. This analyzer is + implemented using Apache Lucene. + + :ivar name: The name of the analyzer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar stopwords: A list of stopwords. + :vartype stopwords: list[str] + :ivar odata_type: A URI fragment specifying the type of analyzer. Required. Default value is + "#Microsoft.Azure.Search.StopAnalyzer". + :vartype odata_type: str + """ + + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of stopwords.""" + odata_type: Literal["#Microsoft.Azure.Search.StopAnalyzer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of analyzer. Required. Default value is + \"#Microsoft.Azure.Search.StopAnalyzer\".""" + + @overload + def __init__( + self, + *, + name: str, + stopwords: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StopAnalyzer" # type: ignore + + +class StopwordsTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StopwordsTokenFilter"): + """Removes stop words from a token stream. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar stopwords: The list of stopwords. This property and the stopwords list property cannot + both be set. + :vartype stopwords: list[str] + :ivar stopwords_list: A predefined list of stopwords to use. This property and the stopwords + property cannot both be set. Default is English. Known values are: "arabic", "armenian", + "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", + "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", + "irish", "italian", "latvian", "norwegian", "persian", "portuguese", "romanian", "russian", + "sorani", "spanish", "swedish", "thai", and "turkish". + :vartype stopwords_list: str or ~azure.search.documents.indexes.models.StopwordsList + :ivar ignore_case: A value indicating whether to ignore case. If true, all words are converted + to lower case first. Default is false. + :vartype ignore_case: bool + :ivar remove_trailing_stop_words: A value indicating whether to ignore the last search term if + it's a stop word. Default is true. + :vartype remove_trailing_stop_words: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.StopwordsTokenFilter". + :vartype odata_type: str + """ + + stopwords: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of stopwords. This property and the stopwords list property cannot both be set.""" + stopwords_list: Optional[Union[str, "_models.StopwordsList"]] = rest_field( + name="stopwordsList", visibility=["read", "create", "update", "delete", "query"] + ) + """A predefined list of stopwords to use. This property and the stopwords property cannot both be + set. Default is English. Known values are: \"arabic\", \"armenian\", \"basque\", \"brazilian\", + \"bulgarian\", \"catalan\", \"czech\", \"danish\", \"dutch\", \"english\", \"finnish\", + \"french\", \"galician\", \"german\", \"greek\", \"hindi\", \"hungarian\", \"indonesian\", + \"irish\", \"italian\", \"latvian\", \"norwegian\", \"persian\", \"portuguese\", \"romanian\", + \"russian\", \"sorani\", \"spanish\", \"swedish\", \"thai\", and \"turkish\".""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to ignore case. If true, all words are converted to lower case + first. Default is false.""" + remove_trailing_stop_words: Optional[bool] = rest_field( + name="removeTrailing", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to ignore the last search term if it's a stop word. Default is true.""" + odata_type: Literal["#Microsoft.Azure.Search.StopwordsTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.StopwordsTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + stopwords: Optional[list[str]] = None, + stopwords_list: Optional[Union[str, "_models.StopwordsList"]] = None, + ignore_case: Optional[bool] = None, + remove_trailing_stop_words: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.StopwordsTokenFilter" # type: ignore + + +class SynonymMap(_Model): + """Represents a synonym map definition. + + :ivar name: The name of the synonym map. Required. + :vartype name: str + :ivar format: The format of the synonym map. Only the 'solr' format is currently supported. + Required. Default value is "solr". + :vartype format: str + :ivar synonyms: A series of synonym rules in the specified synonym map format. The rules must + be separated by newlines. Required. + :vartype synonyms: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your data when you + want full assurance that no one, not even Microsoft, can decrypt your data. Once you have + encrypted your data, it will always remain encrypted. The search service will ignore attempts + to set this property to null. You can change this property as needed if you want to rotate your + encryption key; Your data will be unaffected. Encryption with customer-managed keys is not + available for free search services, and is only available for paid services created on or after + January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar e_tag: The ETag of the synonym map. + :vartype e_tag: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the synonym map. Required.""" + format: Literal["solr"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The format of the synonym map. Only the 'solr' format is currently supported. Required. Default + value is \"solr\".""" + synonyms: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A series of synonym rules in the specified synonym map format. The rules must be separated by + newlines. Required.""" + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( + name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] + ) + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your data when you want full assurance + that no one, not even Microsoft, can decrypt your data. Once you have encrypted your data, it + will always remain encrypted. The search service will ignore attempts to set this property to + null. You can change this property as needed if you want to rotate your encryption key; Your + data will be unaffected. Encryption with customer-managed keys is not available for free search + services, and is only available for paid services created on or after January 1, 2019.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the synonym map.""" + + @overload + def __init__( + self, + *, + name: str, + synonyms: str, + encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.format: Literal["solr"] = "solr" + + +class SynonymTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.SynonymTokenFilter"): + """Matches single or multi-word synonyms in a token stream. This token filter is implemented using + Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar synonyms: A list of synonyms in following one of two formats: 1. incredible, + unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced + with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma + separated list of equivalent words. Set the expand option to change how this list is + interpreted. Required. + :vartype synonyms: list[str] + :ivar ignore_case: A value indicating whether to case-fold input for matching. Default is + false. + :vartype ignore_case: bool + :ivar expand: A value indicating whether all words in the list of synonyms (if => notation is + not used) will map to one another. If true, all words in the list of synonyms (if => notation + is not used) will map to one another. The following list: incredible, unbelievable, fabulous, + amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, + unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, + fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => + incredible. Default is true. + :vartype expand: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.SynonymTokenFilter". + :vartype odata_type: str + """ + + synonyms: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of synonyms in following one of two formats: 1. incredible, unbelievable, fabulous => + amazing - all terms on the left side of => symbol will be replaced with all terms on its right + side; 2. incredible, unbelievable, fabulous, amazing - comma separated list of equivalent + words. Set the expand option to change how this list is interpreted. Required.""" + ignore_case: Optional[bool] = rest_field( + name="ignoreCase", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to case-fold input for matching. Default is false.""" + expand: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether all words in the list of synonyms (if => notation is not used) will + map to one another. If true, all words in the list of synonyms (if => notation is not used) + will map to one another. The following list: incredible, unbelievable, fabulous, amazing is + equivalent to: incredible, unbelievable, fabulous, amazing => incredible, unbelievable, + fabulous, amazing. If false, the following list: incredible, unbelievable, fabulous, amazing + will be equivalent to: incredible, unbelievable, fabulous, amazing => incredible. Default is + true.""" + odata_type: Literal["#Microsoft.Azure.Search.SynonymTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.SynonymTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + synonyms: list[str], + ignore_case: Optional[bool] = None, + expand: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.SynonymTokenFilter" # type: ignore + + +class TagScoringFunction(ScoringFunction, discriminator="tag"): + """Defines a function that boosts scores of documents with string values matching a given list of + tags. + + :ivar field_name: The name of the field used as input to the scoring function. Required. + :vartype field_name: str + :ivar boost: A multiplier for the raw score. Must be a positive number not equal to 1.0. + Required. + :vartype boost: float + :ivar interpolation: A value indicating how boosting will be interpolated across document + scores; defaults to "Linear". Known values are: "linear", "constant", "quadratic", and + "logarithmic". + :vartype interpolation: str or + ~azure.search.documents.indexes.models.ScoringFunctionInterpolation + :ivar parameters: Parameter values for the tag scoring function. Required. + :vartype parameters: ~azure.search.documents.indexes.models.TagScoringParameters + :ivar type: Indicates the type of function to use. Valid values include magnitude, freshness, + distance, and tag. The function type must be lower case. Required. Default value is "tag". + :vartype type: str + """ + + parameters: "_models.TagScoringParameters" = rest_field( + name="tag", visibility=["read", "create", "update", "delete", "query"] + ) + """Parameter values for the tag scoring function. Required.""" + type: Literal["tag"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Indicates the type of function to use. Valid values include magnitude, freshness, distance, and + tag. The function type must be lower case. Required. Default value is \"tag\".""" + + @overload + def __init__( + self, + *, + field_name: str, + boost: float, + parameters: "_models.TagScoringParameters", + interpolation: Optional[Union[str, "_models.ScoringFunctionInterpolation"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "tag" # type: ignore + + +class TagScoringParameters(_Model): + """Provides parameter values to a tag scoring function. + + :ivar tags_parameter: The name of the parameter passed in search queries to specify the list of + tags to compare against the target field. Required. + :vartype tags_parameter: str + """ + + tags_parameter: str = rest_field(name="tagsParameter", visibility=["read", "create", "update", "delete", "query"]) + """The name of the parameter passed in search queries to specify the list of tags to compare + against the target field. Required.""" + + @overload + def __init__( + self, + *, + tags_parameter: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TextTranslationSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Text.TranslationSkill"): + """A skill to translate text from one language to another. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar default_to_language_code: The language code to translate documents into for documents + that don't specify the to language explicitly. Required. Known values are: "af", "ar", "bn", + "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", + "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", + "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", + "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", + "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", and "pa". + :vartype default_to_language_code: str or + ~azure.search.documents.indexes.models.TextTranslationSkillLanguage + :ivar default_from_language_code: The language code to translate documents from for documents + that don't specify the from language explicitly. Known values are: "af", "ar", "bn", "bs", + "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", "fi", + "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", + "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "pt-br", + "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", + "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", and "pa". + :vartype default_from_language_code: str or + ~azure.search.documents.indexes.models.TextTranslationSkillLanguage + :ivar suggested_from: The language code to translate documents from when neither the + fromLanguageCode input nor the defaultFromLanguageCode parameter are provided, and the + automatic language detection is unsuccessful. Default is ``en``. Known values are: "af", "ar", + "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", + "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", + "tlh", "tlh-Latn", "tlh-Piqd", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", + "pt-br", "pt-PT", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", + "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua", "ga", "kn", "mi", "ml", and "pa". + :vartype suggested_from: str or + ~azure.search.documents.indexes.models.TextTranslationSkillLanguage + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Text.TranslationSkill". + :vartype odata_type: str + """ + + default_to_language_code: Union[str, "_models.TextTranslationSkillLanguage"] = rest_field( + name="defaultToLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The language code to translate documents into for documents that don't specify the to language + explicitly. Required. Known values are: \"af\", \"ar\", \"bn\", \"bs\", \"bg\", \"yue\", + \"ca\", \"zh-Hans\", \"zh-Hant\", \"hr\", \"cs\", \"da\", \"nl\", \"en\", \"et\", \"fj\", + \"fil\", \"fi\", \"fr\", \"de\", \"el\", \"ht\", \"he\", \"hi\", \"mww\", \"hu\", \"is\", + \"id\", \"it\", \"ja\", \"sw\", \"tlh\", \"tlh-Latn\", \"tlh-Piqd\", \"ko\", \"lv\", \"lt\", + \"mg\", \"ms\", \"mt\", \"nb\", \"fa\", \"pl\", \"pt\", \"pt-br\", \"pt-PT\", \"otq\", \"ro\", + \"ru\", \"sm\", \"sr-Cyrl\", \"sr-Latn\", \"sk\", \"sl\", \"es\", \"sv\", \"ty\", \"ta\", + \"te\", \"th\", \"to\", \"tr\", \"uk\", \"ur\", \"vi\", \"cy\", \"yua\", \"ga\", \"kn\", + \"mi\", \"ml\", and \"pa\".""" + default_from_language_code: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = rest_field( + name="defaultFromLanguageCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The language code to translate documents from for documents that don't specify the from + language explicitly. Known values are: \"af\", \"ar\", \"bn\", \"bs\", \"bg\", \"yue\", \"ca\", + \"zh-Hans\", \"zh-Hant\", \"hr\", \"cs\", \"da\", \"nl\", \"en\", \"et\", \"fj\", \"fil\", + \"fi\", \"fr\", \"de\", \"el\", \"ht\", \"he\", \"hi\", \"mww\", \"hu\", \"is\", \"id\", + \"it\", \"ja\", \"sw\", \"tlh\", \"tlh-Latn\", \"tlh-Piqd\", \"ko\", \"lv\", \"lt\", \"mg\", + \"ms\", \"mt\", \"nb\", \"fa\", \"pl\", \"pt\", \"pt-br\", \"pt-PT\", \"otq\", \"ro\", \"ru\", + \"sm\", \"sr-Cyrl\", \"sr-Latn\", \"sk\", \"sl\", \"es\", \"sv\", \"ty\", \"ta\", \"te\", + \"th\", \"to\", \"tr\", \"uk\", \"ur\", \"vi\", \"cy\", \"yua\", \"ga\", \"kn\", \"mi\", + \"ml\", and \"pa\".""" + suggested_from: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = rest_field( + name="suggestedFrom", visibility=["read", "create", "update", "delete", "query"] + ) + """The language code to translate documents from when neither the fromLanguageCode input nor the + defaultFromLanguageCode parameter are provided, and the automatic language detection is + unsuccessful. Default is ``en``. Known values are: \"af\", \"ar\", \"bn\", \"bs\", \"bg\", + \"yue\", \"ca\", \"zh-Hans\", \"zh-Hant\", \"hr\", \"cs\", \"da\", \"nl\", \"en\", \"et\", + \"fj\", \"fil\", \"fi\", \"fr\", \"de\", \"el\", \"ht\", \"he\", \"hi\", \"mww\", \"hu\", + \"is\", \"id\", \"it\", \"ja\", \"sw\", \"tlh\", \"tlh-Latn\", \"tlh-Piqd\", \"ko\", \"lv\", + \"lt\", \"mg\", \"ms\", \"mt\", \"nb\", \"fa\", \"pl\", \"pt\", \"pt-br\", \"pt-PT\", \"otq\", + \"ro\", \"ru\", \"sm\", \"sr-Cyrl\", \"sr-Latn\", \"sk\", \"sl\", \"es\", \"sv\", \"ty\", + \"ta\", \"te\", \"th\", \"to\", \"tr\", \"uk\", \"ur\", \"vi\", \"cy\", \"yua\", \"ga\", + \"kn\", \"mi\", \"ml\", and \"pa\".""" + odata_type: Literal["#Microsoft.Skills.Text.TranslationSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Text.TranslationSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + default_to_language_code: Union[str, "_models.TextTranslationSkillLanguage"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + default_from_language_code: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, + suggested_from: Optional[Union[str, "_models.TextTranslationSkillLanguage"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Text.TranslationSkill" # type: ignore + + +class TextWeights(_Model): + """Defines weights on index fields for which matches should boost scoring in search queries. + + :ivar weights: The dictionary of per-field weights to boost document scoring. The keys are + field names and the values are the weights for each field. Required. + :vartype weights: dict[str, float] + """ + + weights: dict[str, float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The dictionary of per-field weights to boost document scoring. The keys are field names and the + values are the weights for each field. Required.""" + + @overload + def __init__( + self, + *, + weights: dict[str, float], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TruncateTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.TruncateTokenFilter"): + """Truncates the terms to a specific length. This token filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar length: The length at which terms will be truncated. Default and maximum is 300. + :vartype length: int + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.TruncateTokenFilter". + :vartype odata_type: str + """ + + length: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The length at which terms will be truncated. Default and maximum is 300.""" + odata_type: Literal["#Microsoft.Azure.Search.TruncateTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.TruncateTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.TruncateTokenFilter" # type: ignore -class SearchIndexerSkillset(_serialization.Model): - """A list of skills. - All required parameters must be populated in order to send to Azure. +class UaxUrlEmailTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.UaxUrlEmailTokenizer"): + """Tokenizes urls and emails as one token. This tokenizer is implemented using Apache Lucene. - :ivar name: The name of the skillset. Required. + :ivar name: The name of the tokenizer. It must only contain letters, digits, spaces, dashes or + underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. :vartype name: str - :ivar description: The description of the skillset. - :vartype description: str - :ivar skills: A list of skills in the skillset. Required. - :vartype skills: list[~azure.search.documents.indexes.models.SearchIndexerSkill] - :ivar cognitive_services_account: Details about the Azure AI service to be used when running - skills. - :vartype cognitive_services_account: ~azure.search.documents.indexes.models.CognitiveServicesAccount - :ivar knowledge_store: Definition of additional projections to Azure blob, table, or files, of - enriched data. - :vartype knowledge_store: ~azure.search.documents.indexes.models.SearchIndexerKnowledgeStore - :ivar index_projection: Definition of additional projections to secondary search index(es). - :vartype index_projection: ~azure.search.documents.indexes.models.SearchIndexerIndexProjection - :ivar e_tag: The ETag of the skillset. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your skillset - definition when you want full assurance that no one, not even Microsoft, can decrypt your - skillset definition. Once you have encrypted your skillset definition, it will always remain - encrypted. The search service will ignore attempts to set this property to null. You can change - this property as needed if you want to rotate your encryption key; Your skillset definition - will be unaffected. Encryption with customer-managed keys is not available for free search - services, and is only available for paid services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + :ivar max_token_length: The maximum token length. Default is 255. Tokens longer than the + maximum length are split. The maximum token length that can be used is 300 characters. + :vartype max_token_length: int + :ivar odata_type: A URI fragment specifying the type of tokenizer. Required. Default value is + "#Microsoft.Azure.Search.UaxUrlEmailTokenizer". + :vartype odata_type: str """ + max_token_length: Optional[int] = rest_field( + name="maxTokenLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum token length. Default is 255. Tokens longer than the maximum length are split. The + maximum token length that can be used is 300 characters.""" + odata_type: Literal["#Microsoft.Azure.Search.UaxUrlEmailTokenizer"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of tokenizer. Required. Default value is + \"#Microsoft.Azure.Search.UaxUrlEmailTokenizer\".""" + + @overload def __init__( self, *, name: str, - skills: List["SearchIndexerSkill"], - description: Optional[str] = None, - cognitive_services_account: Optional["CognitiveServicesAccount"] = None, - knowledge_store: Optional["SearchIndexerKnowledgeStore"] = None, - index_projection: Optional["SearchIndexerIndexProjection"] = None, - e_tag: Optional[str] = None, - encryption_key: Optional["SearchResourceEncryptionKey"] = None, - **kwargs: Any - ) -> None: - super().__init__(**kwargs) - self.name = name - self.description = description - self.skills = skills - self.cognitive_services_account = cognitive_services_account - self.knowledge_store = knowledge_store - self.index_projection = index_projection - self.e_tag = e_tag - self.encryption_key = encryption_key - - def _to_generated(self) -> _SearchIndexerSkillset: - generated_skills = [] - for skill in self.skills: - if hasattr(skill, "_to_generated"): - generated_skills.append(skill._to_generated()) # pylint:disable=protected-access - else: - generated_skills.append(skill) - assert len(generated_skills) == len(self.skills) - encryption_key = getattr(self, "encryption_key", None) - return _SearchIndexerSkillset( - name=getattr(self, "name", ""), - description=getattr(self, "description", None), - skills=generated_skills, - cognitive_services_account=getattr(self, "cognitive_services_account", None), - knowledge_store=getattr(self, "knowledge_store", None), - index_projection=getattr(self, "index_projection", None), - e_tag=getattr(self, "e_tag", None), - encryption_key=( - encryption_key._to_generated() if encryption_key else None # pylint:disable=protected-access - ), - ) - - @classmethod - def _from_generated(cls, skillset) -> Optional[Self]: - if not skillset: - return None - custom_skills = [] - for skill in skillset.skills: - skill_cls = type(skill) - if skill_cls in [_EntityRecognitionSkillV3]: - custom_skills.append(EntityRecognitionSkill._from_generated(skill)) # pylint:disable=protected-access - elif skill_cls in [_SentimentSkillV3]: - custom_skills.append(SentimentSkill._from_generated(skill)) # pylint:disable=protected-access - else: - custom_skills.append(skill) - assert len(skillset.skills) == len(custom_skills) - kwargs = skillset.as_dict() - # pylint:disable=protected-access - kwargs["encryption_key"] = SearchResourceEncryptionKey._from_generated(skillset.encryption_key) - kwargs["skills"] = custom_skills - return cls(**kwargs) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndexerSkillset instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerSkillset instance - :rtype: SearchIndexerSkillset - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndexerSkillset.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerSkillset instance - :rtype: SearchIndexerSkillset - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchIndexerSkillset.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class EntityRecognitionSkillVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the Entity Recognition skill version to use.""" - - V1 = "#Microsoft.Skills.Text.EntityRecognitionSkill" - #: Use Entity Recognition skill V3. - V3 = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill" - #: Use latest version of Entity Recognition skill. - LATEST = V3 - - -class EntityRecognitionSkill(SearchIndexerSkill): - """Using the Text Analytics API, extracts entities of different types from text. + max_token_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer" # type: ignore - All required parameters must be populated in order to send to Azure. - :ivar odata_type: Required. Identifies the concrete type of the skill.Constant filled by - server. +class UniqueTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.UniqueTokenFilter"): + """Filters out tokens with same text as the previous token. This token filter is implemented using + Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. + :vartype name: str + :ivar only_on_same_position: A value indicating whether to remove duplicates only at the same + position. Default is false. + :vartype only_on_same_position: bool + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.UniqueTokenFilter". :vartype odata_type: str + """ + + only_on_same_position: Optional[bool] = rest_field( + name="onlyOnSamePosition", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to remove duplicates only at the same position. Default is false.""" + odata_type: Literal["#Microsoft.Azure.Search.UniqueTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.UniqueTokenFilter\".""" + + @overload + def __init__( + self, + *, + name: str, + only_on_same_position: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.UniqueTokenFilter" # type: ignore + + +class VectorSearch(_Model): + """Contains configuration options related to vector search. + + :ivar profiles: Defines combinations of configurations to use with vector search. + :vartype profiles: list[~azure.search.documents.indexes.models.VectorSearchProfile] + :ivar algorithms: Contains configuration options specific to the algorithm used during indexing + or querying. + :vartype algorithms: + list[~azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration] + :ivar vectorizers: Contains configuration options on how to vectorize text vector queries. + :vartype vectorizers: list[~azure.search.documents.indexes.models.VectorSearchVectorizer] + :ivar compressions: Contains configuration options specific to the compression method used + during indexing or querying. + :vartype compressions: list[~azure.search.documents.indexes.models.VectorSearchCompression] + """ + + profiles: Optional[list["_models.VectorSearchProfile"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Defines combinations of configurations to use with vector search.""" + algorithms: Optional[list["_models.VectorSearchAlgorithmConfiguration"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options specific to the algorithm used during indexing or querying.""" + vectorizers: Optional[list["_models.VectorSearchVectorizer"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options on how to vectorize text vector queries.""" + compressions: Optional[list["_models.VectorSearchCompression"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Contains configuration options specific to the compression method used during indexing or + querying.""" + + @overload + def __init__( + self, + *, + profiles: Optional[list["_models.VectorSearchProfile"]] = None, + algorithms: Optional[list["_models.VectorSearchAlgorithmConfiguration"]] = None, + vectorizers: Optional[list["_models.VectorSearchVectorizer"]] = None, + compressions: Optional[list["_models.VectorSearchCompression"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorSearchProfile(_Model): + """Defines a combination of configurations to use with vector search. + + :ivar name: The name to associate with this particular vector search profile. Required. + :vartype name: str + :ivar algorithm_configuration_name: The name of the vector search algorithm configuration that + specifies the algorithm and optional parameters. Required. + :vartype algorithm_configuration_name: str + :ivar vectorizer_name: The name of the vectorization being configured for use with vector + search. + :vartype vectorizer_name: str + :ivar compression_name: The name of the compression method configuration that specifies the + compression method and optional parameters. + :vartype compression_name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name to associate with this particular vector search profile. Required.""" + algorithm_configuration_name: str = rest_field( + name="algorithm", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the vector search algorithm configuration that specifies the algorithm and optional + parameters. Required.""" + vectorizer_name: Optional[str] = rest_field( + name="vectorizer", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the vectorization being configured for use with vector search.""" + compression_name: Optional[str] = rest_field( + name="compression", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the compression method configuration that specifies the compression method and + optional parameters.""" + + @overload + def __init__( + self, + *, + name: str, + algorithm_configuration_name: str, + vectorizer_name: Optional[str] = None, + compression_name: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VisionVectorizeSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Vision.VectorizeSkill"): + """Allows you to generate a vector embedding for a given image or text input using the Azure AI + Services Vision Vectorize API. + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill with no name defined will be given a default name of its 1-based index in the skills array, prefixed with the character '#'. @@ -232,123 +11320,59 @@ class EntityRecognitionSkill(SearchIndexerSkill): :ivar context: Represents the level at which operations take place, such as the document root or document content (for example, /document or /document/content). The default is /document. :vartype context: str - :ivar inputs: Required. Inputs of the skills could be a column in the source data set, or the - output of an upstream skill. + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: Required. The output of a skill is either a field in a search index, or a value - that can be consumed as an input by another skill. + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar categories: A list of entity categories that should be extracted. - :vartype categories: list[str] or list[~azure.search.documents.indexes.models.EntityCategory] - :ivar default_language_code: A value indicating which language code to use. Default is en. - Possible values include: "ar", "cs", "zh-Hans", "zh-Hant", "da", "nl", "en", "fi", "fr", "de", - "el", "hu", "it", "ja", "ko", "no", "pl", "pt-PT", "pt-BR", "ru", "es", "sv", "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.EntityRecognitionSkillLanguage - :ivar include_typeless_entities: Determines whether or not to include entities which are well - known but don't conform to a pre-defined type. If this configuration is not set (default), set - to null or set to false, entities which don't conform to one of the pre-defined types will not - be surfaced. Only valid for skill version 1. - :vartype include_typeless_entities: bool - :ivar minimum_precision: A value between 0 and 1 that be used to only include entities whose - confidence score is greater than the value specified. If not set (default), or if explicitly - set to null, all entities will be included. - :vartype minimum_precision: float - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. Only valid from skill version 3. + :ivar model_version: The version of the model to use when calling the AI Services Vision + service. It will default to the latest available when not specified. Required. :vartype model_version: str - :ivar skill_version: The version of the skill to use when calling the Text Analytics service. - It will default to V1 when not specified. - :vartype skill_version: ~azure.search.documents.indexes.models.EntityRecognitionSkillVersion - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - "minimum_precision": {"maximum": 1, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "categories": {"key": "categories", "type": "[str]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_typeless_entities": {"key": "includeTypelessEntities", "type": "bool"}, - "minimum_precision": {"key": "minimumPrecision", "type": "float"}, - "model_version": {"key": "modelVersion", "type": "str"}, - "skill_version": {"key": "skillVersion", "type": "str"}, - } - - def __init__(self, **kwargs): - # pop skill_version from kwargs to avoid warning in msrest - skill_version = kwargs.pop("skill_version", EntityRecognitionSkillVersion.V3) - - super(EntityRecognitionSkill, self).__init__(**kwargs) - self.skill_version = skill_version - self.odata_type = self.skill_version - self.categories = kwargs.get("categories", None) - self.default_language_code = kwargs.get("default_language_code", None) - self.minimum_precision = kwargs.get("minimum_precision", None) - self.include_typeless_entities = kwargs.get("include_typeless_entities", None) - self.model_version = kwargs.get("model_version", None) - - def _to_generated(self): - if self.skill_version in [ - EntityRecognitionSkillVersion.V3, - EntityRecognitionSkillVersion.LATEST, - ]: - return _EntityRecognitionSkillV3( - inputs=self.inputs, - outputs=self.outputs, - name=self.name, - description=self.description, - context=self.context, - odata_type=self.odata_type, - categories=self.categories, - default_language_code=self.default_language_code, - minimum_precision=self.minimum_precision, - model_version=self.model_version, - ) - return None - - @classmethod - def _from_generated(cls, skill): - if not skill: - return None - kwargs = skill.as_dict() - if isinstance(skill, _EntityRecognitionSkillV3): - return EntityRecognitionSkill(skill_version=EntityRecognitionSkillVersion.V3, **kwargs) - return None - - -class SentimentSkillVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the Sentiment Skill version to use.""" - - V1 = "#Microsoft.Skills.Text.SentimentSkill" - #: Use Sentiment skill V3. - V3 = "#Microsoft.Skills.Text.V3.SentimentSkill" - #: Use latest version of Sentiment skill. - LATEST = V3 - - -class SentimentSkill(SearchIndexerSkill): - """V1: Text analytics positive-negative sentiment analysis, scored as a floating point value in a range of zero - to 1. - V3: Using the Text Analytics API, evaluates unstructured text and for each record, provides sentiment labels - (such as "negative", "neutral" and "positive") based on the highest confidence score found by the service at - a sentence and document-level. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: Required. Identifies the concrete type of the skill.Constant filled by - server. + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Vision.VectorizeSkill". :vartype odata_type: str + """ + + model_version: str = rest_field(name="modelVersion", visibility=["read", "create", "update", "delete", "query"]) + """The version of the model to use when calling the AI Services Vision service. It will default to + the latest available when not specified. Required.""" + odata_type: Literal["#Microsoft.Skills.Vision.VectorizeSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Vision.VectorizeSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + model_version: str, + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Vision.VectorizeSkill" # type: ignore + + +class WebApiHttpHeaders(_Model): + """A dictionary of http request headers.""" + + +class WebApiSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.WebApiSkill"): + """A skill that can call a Web API endpoint, allowing you to extend a skillset by having it call + your custom code. + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill with no name defined will be given a default name of its 1-based index in the skills array, prefixed with the character '#'. @@ -359,1085 +11383,349 @@ class SentimentSkill(SearchIndexerSkill): :ivar context: Represents the level at which operations take place, such as the document root or document content (for example, /document or /document/content). The default is /document. :vartype context: str - :ivar inputs: Required. Inputs of the skills could be a column in the source data set, or the - output of an upstream skill. + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] - :ivar outputs: Required. The output of a skill is either a field in a search index, or a value - that can be consumed as an input by another skill. + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar default_language_code: A value indicating which language code to use. Default is en. - Possible values include: "da", "nl", "en", "fi", "fr", "de", "el", "it", "no", "pl", "pt-PT", - "ru", "es", "sv", "tr". - :vartype default_language_code: str or - ~azure.search.documents.indexes.models.SentimentSkillLanguage - :ivar include_opinion_mining: If set to true, the skill output will include information from - Text Analytics for opinion mining, namely targets (nouns or verbs) and their associated - assessment (adjective) in the text. Default is false. - :vartype include_opinion_mining: bool - :ivar model_version: The version of the model to use when calling the Text Analytics service. - It will default to the latest available when not specified. We recommend you do not specify - this value unless absolutely necessary. - :vartype model_version: str - :ivar skill_version: The version of the skill to use when calling the Text Analytics service. - It will default to V1 when not specified. - :vartype skill_version: ~azure.search.documents.indexes.models.SentimentSkillVersion - """ - - _validation = { - "odata_type": {"required": True}, - "inputs": {"required": True}, - "outputs": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "context": {"key": "context", "type": "str"}, - "inputs": {"key": "inputs", "type": "[InputFieldMappingEntry]"}, - "outputs": {"key": "outputs", "type": "[OutputFieldMappingEntry]"}, - "default_language_code": {"key": "defaultLanguageCode", "type": "str"}, - "include_opinion_mining": {"key": "includeOpinionMining", "type": "bool"}, - "model_version": {"key": "modelVersion", "type": "str"}, - "skill_version": {"key": "skillVersion", "type": "str"}, - } - - def __init__(self, **kwargs): - # pop skill_version from kwargs to avoid warning in msrest - skill_version = kwargs.pop("skill_version", SentimentSkillVersion.V3) - - super(SentimentSkill, self).__init__(**kwargs) - self.skill_version = skill_version - self.odata_type = self.skill_version - self.default_language_code = kwargs.get("default_language_code", None) - self.include_opinion_mining = kwargs.get("include_opinion_mining", None) - self.model_version = kwargs.get("model_version", None) - - def _to_generated(self): - if self.skill_version in [ - SentimentSkillVersion.V3, - SentimentSkillVersion.LATEST, - ]: - return _SentimentSkillV3( - inputs=self.inputs, - outputs=self.outputs, - name=self.name, - description=self.description, - context=self.context, - odata_type=self.odata_type, - default_language_code=self.default_language_code, - include_opinion_mining=self.include_opinion_mining, - model_version=self.model_version, - ) - return None - - @classmethod - def _from_generated(cls, skill): - if not skill: - return None - kwargs = skill.as_dict() - if isinstance(skill, _SentimentSkillV3): - return SentimentSkill(skill_version=SentimentSkillVersion.V3, **kwargs) - return None - - -class AnalyzeTextOptions(_serialization.Model): - """Specifies some text and analysis components used to break that text into tokens.""" + :ivar uri: The url for the Web API. Required. + :vartype uri: str + :ivar http_headers: The headers required to make the http request. + :vartype http_headers: dict[str, str] + :ivar http_method: The method for the http request. + :vartype http_method: str + :ivar timeout: The desired timeout for the request. Default is 30 seconds. + :vartype timeout: ~datetime.timedelta + :ivar batch_size: The desired batch size which indicates number of documents. + :vartype batch_size: int + :ivar degree_of_parallelism: If set, the number of parallel calls that can be made to the Web + API. + :vartype degree_of_parallelism: int + :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure + function or some other application that provides the transformations. This value should be the + application ID created for the function or app when it was registered with Azure Active + Directory. When specified, the custom skill connects to the function or app using a managed ID + (either system or user-assigned) of the search service and the access token of the function or + app, using this value as the resource id for creating the scope of the access token. + :vartype auth_resource_id: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. + If set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Custom.WebApiSkill". + :vartype odata_type: str + """ + uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url for the Web API. Required.""" + http_headers: Optional[dict[str, str]] = rest_field( + name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """The headers required to make the http request.""" + http_method: Optional[str] = rest_field( + name="httpMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The method for the http request.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The desired timeout for the request. Default is 30 seconds.""" + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) + """The desired batch size which indicates number of documents.""" + degree_of_parallelism: Optional[int] = rest_field( + name="degreeOfParallelism", visibility=["read", "create", "update", "delete", "query"] + ) + """If set, the number of parallel calls that can be made to the Web API.""" + auth_resource_id: Optional[str] = rest_field( + name="authResourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """Applies to custom skills that connect to external code in an Azure function or some other + application that provides the transformations. This value should be the application ID created + for the function or app when it was registered with Azure Active Directory. When specified, the + custom skill connects to the function or app using a managed ID (either system or + user-assigned) of the search service and the access token of the function or app, using this + value as the resource id for creating the scope of the access token.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", + the value of this property is cleared.""" + odata_type: Literal["#Microsoft.Skills.Custom.WebApiSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Custom.WebApiSkill\".""" + + @overload def __init__( self, *, - text: str, - analyzer_name: Optional[str] = None, - tokenizer_name: Optional[str] = None, - normalizer_name: Optional[str] = None, - token_filters: Optional[List[str]] = None, - char_filters: Optional[List[str]] = None, - **kwargs - ): - """ - :keyword text: Required. The text to break into tokens. - :paramtype text: str - :keyword analyzer_name: The name of the analyzer to use to break the given text. If this parameter is - not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are - mutually exclusive. Possible values include: "ar.microsoft", "ar.lucene", "hy.lucene", - "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh- - Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", - "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", - "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", - "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", - "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", - "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", - "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", - "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", - "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt- - PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", - "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", - "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", - "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", - "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", - "simple", "stop", "whitespace". - :paramtype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :keyword tokenizer_name: The name of the tokenizer to use to break the given text. If this parameter - is not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters - are mutually exclusive. Possible values include: "classic", "edgeNGram", "keyword_v2", - "letter", "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", - "nGram", "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", "whitespace". - :paramtype tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :keyword token_filters: An optional list of token filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :paramtype token_filters: list[str] or list[~azure.search.documents.indexes.models.TokenFilterName] - :keyword char_filters: An optional list of character filters to use when breaking the given text. - This parameter can only be set when using the tokenizer parameter. - :paramtype char_filters: list[str] - """ - super().__init__(**kwargs) - self.text = text - self.analyzer_name = analyzer_name - self.tokenizer_name = tokenizer_name - self.normalizer_name = normalizer_name - self.token_filters = token_filters - self.char_filters = char_filters - - def _to_analyze_request(self): - return AnalyzeRequest( - text=self.text, - analyzer=self.analyzer_name, - tokenizer=self.tokenizer_name, - normalizer=self.normalizer_name, - token_filters=self.token_filters, - char_filters=self.char_filters, - ) - - @classmethod - def _from_analyze_request(cls, analyze_request) -> Optional[Self]: - if not analyze_request: - return None - return cls( - text=analyze_request.text, - analyzer_name=analyze_request.analyzer, - tokenizer_name=analyze_request.tokenizer, - normalizer_name=analyze_request.normalizer, - token_filters=analyze_request.token_filters, - char_filters=analyze_request.char_filters, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_analyze_request().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a AnalyzeTextOptions instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A AnalyzeTextOptions instance - :rtype: AnalyzeTextOptions - :raises DeserializationError: if something went wrong - """ - return cls._from_analyze_request(AnalyzeRequest.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_analyze_request().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A AnalyzeTextOptions instance - :rtype: AnalyzeTextOptions - :raises DeserializationError: if something went wrong - """ - return cls._from_analyze_request( - AnalyzeRequest.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class CustomAnalyzer(LexicalAnalyzer): - """Allows you to take control over the process of converting text into indexable/searchable tokens. - It's a user-defined configuration consisting of a single predefined tokenizer and one or more filters. - The tokenizer is responsible for breaking text into tokens, and the filters for modifying tokens - emitted by the tokenizer. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: Required. Identifies the concrete type of the analyzer.Constant filled by - server. - :vartype odata_type: str - :ivar name: Required. The name of the analyzer. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. - :vartype name: str - :ivar tokenizer_name: Required. The name of the tokenizer to use to divide continuous text into a - sequence of tokens, such as breaking a sentence into words. Possible values include: "classic", - "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", - "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", - "standard_v2", "uax_url_email", "whitespace". - :vartype tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar token_filters: A list of token filters used to filter out or modify the tokens generated - by a tokenizer. For example, you can specify a lowercase filter that converts all characters to - lowercase. The filters are run in the order in which they are listed. - :vartype token_filters: list[str] or list[~azure.search.documents.indexes.models.TokenFilterName] - :ivar char_filters: A list of character filters used to prepare input text before it is - processed by the tokenizer. For instance, they can replace certain characters or symbols. The - filters are run in the order in which they are listed. - :vartype char_filters: list[str] - """ - - def __init__(self, **kwargs): - super(CustomAnalyzer, self).__init__(**kwargs) - self.odata_type = "#Microsoft.Azure.Search.CustomAnalyzer" - self.tokenizer_name = kwargs["tokenizer_name"] - self.token_filters = kwargs.get("token_filters", None) - self.char_filters = kwargs.get("char_filters", None) - - def _to_generated(self): - return _CustomAnalyzer( - name=self.name, - odata_type=self.odata_type, - tokenizer=self.tokenizer_name, - token_filters=self.token_filters, - char_filters=self.char_filters, - ) - - @classmethod - def _from_generated(cls, custom_analyzer): - if not custom_analyzer: - return None - return cls( - name=custom_analyzer.name, - odata_type=custom_analyzer.odata_type, - tokenizer_name=custom_analyzer.tokenizer, - token_filters=custom_analyzer.token_filters, - char_filters=custom_analyzer.char_filters, - ) - - -class PatternAnalyzer(LexicalAnalyzer): - """Flexibly separates text into terms via a regular expression. - This analyzer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to Azure. - - :ivar name: Required. The name of the analyzer. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. - :vartype name: str - :ivar lower_case_terms: A value indicating whether terms should be lower-cased. Default is - true. - :vartype lower_case_terms: bool - :ivar pattern: A regular expression to match token separators. Default is an - expression that matches one or more white space characters. - :vartype pattern: str - :ivar flags: List of regular expression flags. Possible values of each flag include: 'CANON_EQ', - 'CASE_INSENSITIVE', 'COMMENTS', 'DOTALL', 'LITERAL', 'MULTILINE', 'UNICODE_CASE', 'UNIX_LINES'. - :vartype flags: list[str] or list[~azure.search.documents.indexes.models.RegexFlags] - :ivar stopwords: A list of stopwords. - :vartype stopwords: list[str] - """ + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + uri: str, + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + http_headers: Optional[dict[str, str]] = None, + http_method: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + batch_size: Optional[int] = None, + degree_of_parallelism: Optional[int] = None, + auth_resource_id: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ - _validation = {"odata_type": {"required": True}, "name": {"required": True}} - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "lower_case_terms": {"key": "lowercase", "type": "bool"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "[str]"}, - "stopwords": {"key": "stopwords", "type": "[str]"}, - } - - def __init__(self, **kwargs): - super(PatternAnalyzer, self).__init__(**kwargs) - self.odata_type = "#Microsoft.Azure.Search.PatternAnalyzer" - self.lower_case_terms = kwargs.get("lower_case_terms", True) - self.pattern = kwargs.get("pattern", r"\W+") - self.flags = kwargs.get("flags", None) - self.stopwords = kwargs.get("stopwords", None) - - def _to_generated(self): - if not self.flags: - flags = None - else: - flags = DELIMITER.join(self.flags) - return _PatternAnalyzer( - name=self.name, - lower_case_terms=self.lower_case_terms, - pattern=self.pattern, - flags=flags, - stopwords=self.stopwords, - ) - - @classmethod - def _from_generated(cls, pattern_analyzer): - if not pattern_analyzer: - return None - if not pattern_analyzer.flags: - flags = None - else: - flags = pattern_analyzer.flags.split(DELIMITER) - return cls( - name=pattern_analyzer.name, - lower_case_terms=pattern_analyzer.lower_case_terms, - pattern=pattern_analyzer.pattern, - flags=flags, - stopwords=pattern_analyzer.stopwords, - ) - - -class PatternTokenizer(LexicalTokenizer): - """Tokenizer that uses regex pattern matching to construct distinct tokens. - This tokenizer is implemented using Apache Lucene. - - All required parameters must be populated in order to send to Azure. - - :ivar name: Required. The name of the tokenizer. It must only contain letters, digits, spaces, - dashes or underscores, can only start and end with alphanumeric characters, and is limited to - 128 characters. - :vartype name: str - :ivar pattern: A regular expression to match token separators. Default is an - expression that matches one or more white space characters. - :vartype pattern: str - :ivar flags: List of regular expression flags. Possible values of each flag include: 'CANON_EQ', - 'CASE_INSENSITIVE', 'COMMENTS', 'DOTALL', 'LITERAL', 'MULTILINE', 'UNICODE_CASE', 'UNIX_LINES'. - :vartype flags: list[str] or list[~azure.search.documents.indexes.models.RegexFlags] - :ivar group: The zero-based ordinal of the matching group in the regular expression to - extract into tokens. Use -1 if you want to use the entire pattern to split the input into - tokens, irrespective of matching groups. Default is -1. - :vartype group: int - """ + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.WebApiSkill" # type: ignore - _validation = {"odata_type": {"required": True}, "name": {"required": True}} - - _attribute_map = { - "odata_type": {"key": "@odata\\.type", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "pattern": {"key": "pattern", "type": "str"}, - "flags": {"key": "flags", "type": "[str]"}, - "group": {"key": "group", "type": "int"}, - } - - def __init__(self, **kwargs): - super(PatternTokenizer, self).__init__(**kwargs) - self.odata_type = "#Microsoft.Azure.Search.PatternTokenizer" - self.pattern = kwargs.get("pattern", r"\W+") - self.flags = kwargs.get("flags", None) - self.group = kwargs.get("group", -1) - - def _to_generated(self): - if not self.flags: - flags = None - else: - flags = DELIMITER.join(self.flags) - return _PatternTokenizer( - name=self.name, - pattern=self.pattern, - flags=flags, - group=self.group, - ) - - @classmethod - def _from_generated(cls, pattern_tokenizer): - if not pattern_tokenizer: - return None - if not pattern_tokenizer.flags: - flags = None - else: - flags = pattern_tokenizer.flags.split(DELIMITER) - return cls( - name=pattern_tokenizer.name, - pattern=pattern_tokenizer.pattern, - flags=flags, - group=pattern_tokenizer.group, - ) - - -class SearchResourceEncryptionKey(_serialization.Model): - """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be - used to encrypt or decrypt data-at-rest in Azure Cognitive Search, such as indexes and synonym maps. - All required parameters must be populated in order to send to Azure. +class WebApiVectorizer(VectorSearchVectorizer, discriminator="customWebApi"): + """Specifies a user-defined vectorizer for generating the vector embedding of a query string. + Integration of an external vectorizer is achieved using the custom Web API interface of a + skillset. - :ivar key_name: Required. The name of your Azure Key Vault key to be used to encrypt your data - at rest. - :vartype key_name: str - :ivar key_version: Required. The version of your Azure Key Vault key to be used to encrypt - your data at rest. - :vartype key_version: str - :ivar vault_uri: Required. The URI of your Azure Key Vault, also referred to as DNS name, that - contains the key to be used to encrypt your data at rest. An example URI might be https://my- - keyvault-name.vault.azure.net. - :vartype vault_uri: str - :ivar application_id: Required. An AAD Application ID that was granted the required access - permissions to the Azure Key Vault that is to be used when encrypting your data at rest. The - Application ID should not be confused with the Object ID for your AAD Application. - :vartype application_id: str - :ivar application_secret: The authentication key of the specified AAD application. - :vartype application_secret: str - :ivar identity: An explicit managed identity to use for this encryption key. If not specified - and the access credentials property is null, the system-assigned managed identity is used. On - update to the resource, if the explicit identity is unspecified, it remains unchanged. If - "none" is specified, the value of this property is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar vectorizer_name: The name to associate with this particular vectorization method. + Required. + :vartype vectorizer_name: str + :ivar web_api_parameters: Specifies the properties of the user-defined vectorizer. + :vartype web_api_parameters: ~azure.search.documents.indexes.models.WebApiVectorizerParameters + :ivar kind: The name of the kind of vectorization method being configured for use with vector + search. Required. Generate embeddings using a custom web endpoint at query time. + :vartype kind: str or ~azure.search.documents.indexes.models.CUSTOM_WEB_API """ + web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = rest_field( + name="customWebApiParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the properties of the user-defined vectorizer.""" + kind: Literal[VectorSearchVectorizerKind.CUSTOM_WEB_API] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The name of the kind of vectorization method being configured for use with vector search. + Required. Generate embeddings using a custom web endpoint at query time.""" + + @overload def __init__( self, *, - key_name: str, - key_version: str, - vault_uri: str, - application_id: Optional[str] = None, - application_secret: Optional[str] = None, - identity: Optional[SearchIndexerDataIdentity] = None, - **kwargs - ): - super().__init__(**kwargs) - self.key_name = key_name - self.key_version = key_version - self.vault_uri = vault_uri - self.application_id = application_id - self.application_secret = application_secret - self.identity = identity - - def _to_generated(self): - if self.application_id and self.application_secret: - access_credentials = AzureActiveDirectoryApplicationCredentials( - application_id=self.application_id, - application_secret=self.application_secret, - ) - else: - access_credentials = None - return _SearchResourceEncryptionKey( - key_name=self.key_name, - key_version=self.key_version, - vault_uri=self.vault_uri, - access_credentials=access_credentials, - identity=self.identity, - ) - - @classmethod - def _from_generated(cls, search_resource_encryption_key) -> Optional[Self]: - if not search_resource_encryption_key: - return None - if search_resource_encryption_key.access_credentials: - application_id = search_resource_encryption_key.access_credentials.application_id - application_secret = search_resource_encryption_key.access_credentials.application_secret - else: - application_id = None - application_secret = None - return cls( - key_name=search_resource_encryption_key.key_name, - key_version=search_resource_encryption_key.key_version, - vault_uri=search_resource_encryption_key.vault_uri, - application_id=application_id, - application_secret=application_secret, - identity=search_resource_encryption_key.identity, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchResourceEncryptionKey instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchResourceEncryptionKey instance - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( # type: ignore - _SearchResourceEncryptionKey.deserialize(data, content_type=content_type) - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchResourceEncryptionKey instance - :rtype: SearchResourceEncryptionKey - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchResourceEncryptionKey.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class SynonymMap(_serialization.Model): - """Represents a synonym map definition. + vectorizer_name: str, + web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = None, + ) -> None: ... - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ - :ivar name: Required. The name of the synonym map. - :vartype name: str - :ivar format: Required. The format of the synonym map. Only the 'solr' format is currently - supported. Default value: "solr". - :vartype format: str - :ivar synonyms: Required. A series of synonym rules in the specified synonym map format. The - rules must be separated by newlines. - :vartype synonyms: list[str] - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your data when you - want full assurance that no one, not even Microsoft, can decrypt your data in Azure Cognitive - Search. Once you have encrypted your data, it will always remain encrypted. Azure Cognitive - Search will ignore attempts to set this property to null. You can change this property as - needed if you want to rotate your encryption key; Your data will be unaffected. Encryption with - customer-managed keys is not available for free search services, and is only available for paid - services created on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar e_tag: The ETag of the synonym map. - :vartype e_tag: str + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorSearchVectorizerKind.CUSTOM_WEB_API # type: ignore + + +class WebApiVectorizerParameters(_Model): + """Specifies the properties for connecting to a user-defined vectorizer. + + :ivar url: The URI of the Web API providing the vectorizer. + :vartype url: str + :ivar http_headers: The headers required to make the HTTP request. + :vartype http_headers: dict[str, str] + :ivar http_method: The method for the HTTP request. + :vartype http_method: str + :ivar timeout: The desired timeout for the request. Default is 30 seconds. + :vartype timeout: ~datetime.timedelta + :ivar auth_resource_id: Applies to custom endpoints that connect to external code in an Azure + function or some other application that provides the transformations. This value should be the + application ID created for the function or app when it was registered with Azure Active + Directory. When specified, the vectorization connects to the function or app using a managed ID + (either system or user-assigned) of the search service and the access token of the function or + app, using this value as the resource id for creating the scope of the access token. + :vartype auth_resource_id: str + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. + If set to "none", the value of this property is cleared. + :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity """ - format = "solr" - + url: Optional[str] = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) + """The URI of the Web API providing the vectorizer.""" + http_headers: Optional[dict[str, str]] = rest_field( + name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """The headers required to make the HTTP request.""" + http_method: Optional[str] = rest_field( + name="httpMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The method for the HTTP request.""" + timeout: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The desired timeout for the request. Default is 30 seconds.""" + auth_resource_id: Optional[str] = rest_field( + name="authResourceId", visibility=["read", "create", "update", "delete", "query"] + ) + """Applies to custom endpoints that connect to external code in an Azure function or some other + application that provides the transformations. This value should be the application ID created + for the function or app when it was registered with Azure Active Directory. When specified, the + vectorization connects to the function or app using a managed ID (either system or + user-assigned) of the search service and the access token of the function or app, using this + value as the resource id for creating the scope of the access token.""" + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( + name="authIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", + the value of this property is cleared.""" + + @overload def __init__( self, *, - name: str, - synonyms: List[str], - encryption_key: Optional[SearchResourceEncryptionKey] = None, - e_tag: Optional[str] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.synonyms = synonyms - self.encryption_key = encryption_key - self.e_tag = e_tag - - def _to_generated(self): - return _SynonymMap( - name=self.name, - synonyms="\n".join(self.synonyms), - encryption_key=( - self.encryption_key._to_generated() if self.encryption_key else None # pylint:disable=protected-access - ), - e_tag=self.e_tag, - ) - - @classmethod - def _from_generated(cls, synonym_map) -> Optional[Self]: - if not synonym_map: - return None - return cls( - name=synonym_map.name, - synonyms=synonym_map.synonyms.split("\n"), - # pylint:disable=protected-access - encryption_key=SearchResourceEncryptionKey._from_generated(synonym_map.encryption_key), - e_tag=synonym_map.e_tag, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SynonymMap instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SynonymMap instance - :rtype: SynonymMap - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SynonymMap.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SynonymMap instance - :rtype: SynonymMap - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SynonymMap.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -class SearchIndexerDataSourceConnection(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Represents a datasource connection definition, which can be used to configure an indexer. - - All required parameters must be populated in order to send to Azure. - - :ivar name: Required. The name of the datasource connection. - :vartype name: str - :ivar description: The description of the datasource connection. - :vartype description: str - :ivar type: Required. The type of the datasource connection. Possible values include: "azuresql", - "cosmosdb", "azureblob", "azuretable", "mysql", "adlsgen2". - :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :ivar connection_string: The connection string for the datasource connection. - :vartype connection_string: str - :ivar container: Required. The data container for the datasource connection. - :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :ivar identity: An explicit managed identity to use for this datasource. If not specified and - the connection string is a managed identity, the system-assigned managed identity is used. If - not specified, the value remains unchanged. If "none" is specified, the value of this property - is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar indexer_permission_options: Ingestion options with various types of permission data. - :vartype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :ivar data_change_detection_policy: The data change detection policy for the datasource connection. - :vartype data_change_detection_policy: ~azure.search.documents.models.DataChangeDetectionPolicy - :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource connection. - :vartype data_deletion_detection_policy: - ~azure.search.documents.models.DataDeletionDetectionPolicy - :ivar e_tag: The ETag of the data source. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition in Azure Cognitive Search. Once you have encrypted your data source - definition, it will always remain encrypted. Azure Cognitive Search will ignore attempts to set - this property to null. You can change this property as needed if you want to rotate your - encryption key; Your datasource definition will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ + url: Optional[str] = None, + http_headers: Optional[dict[str, str]] = None, + http_method: Optional[str] = None, + timeout: Optional[datetime.timedelta] = None, + auth_resource_id: Optional[str] = None, + auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - type: str, - connection_string: str, - container: SearchIndexerDataContainer, - identity: Optional[SearchIndexerDataIdentity] = None, - indexer_permission_options: Optional[List[Union[str, IndexerPermissionOption]]] = None, - data_change_detection_policy: Optional[DataChangeDetectionPolicy] = None, - data_deletion_detection_policy: Optional[DataDeletionDetectionPolicy] = None, - e_tag: Optional[str] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - **kwargs - ): - super().__init__(**kwargs) - self.name = name - self.description = description - self.type = type - self.connection_string = connection_string - self.container = container - self.identity = identity - self.indexer_permission_options = indexer_permission_options - self.data_change_detection_policy = data_change_detection_policy - self.data_deletion_detection_policy = data_deletion_detection_policy - self.e_tag = e_tag - self.encryption_key = encryption_key - - def _to_generated(self): - if self.connection_string is None or self.connection_string == "": - connection_string = "" - else: - connection_string = self.connection_string - credentials = DataSourceCredentials(connection_string=connection_string) - return _SearchIndexerDataSource( - name=self.name, - description=self.description, - type=self.type, - credentials=credentials, - container=self.container, - data_change_detection_policy=self.data_change_detection_policy, - data_deletion_detection_policy=self.data_deletion_detection_policy, - e_tag=self.e_tag, - encryption_key=( - self.encryption_key._to_generated() if self.encryption_key else None # pylint: disable=protected-access - ), - identity=self.identity, - indexer_permission_options=self.indexer_permission_options, - ) - - @classmethod - def _from_generated(cls, search_indexer_data_source) -> Optional[Self]: - if not search_indexer_data_source: - return None - connection_string = ( - search_indexer_data_source.credentials.connection_string if search_indexer_data_source.credentials else "" - ) - return cls( - name=search_indexer_data_source.name, - description=search_indexer_data_source.description, - type=search_indexer_data_source.type, - connection_string=connection_string, - container=search_indexer_data_source.container, - data_change_detection_policy=search_indexer_data_source.data_change_detection_policy, - data_deletion_detection_policy=search_indexer_data_source.data_deletion_detection_policy, - e_tag=search_indexer_data_source.e_tag, - encryption_key=( - SearchResourceEncryptionKey._from_generated( # pylint: disable=protected-access - search_indexer_data_source.encryption_key - ) - if search_indexer_data_source.encryption_key - else None - ), - identity=search_indexer_data_source.identity, - indexer_permission_options=search_indexer_data_source.indexer_permission_options, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndexerDataSourceConnection instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerDataSourceConnection instance - :rtype: SearchIndexerDataSourceConnection - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndexerDataSource.deserialize(data, content_type=content_type)) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = _serialization.attribute_transformer, - **kwargs: Any - ) -> MutableMapping[str, Any]: - """Return a dict that can be serialized using json.dump. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param Callable key_transformer: A callable that will transform the key of the dict - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().as_dict( # type: ignore - keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs - ) - - @classmethod - def from_dict( # type: ignore - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Optional[Self]: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param Callable key_extractors: A callable that will extract a key from a dict - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexerDataSourceConnection instance - :rtype: SearchIndexerDataSourceConnection - :raises DeserializationError: if something went wrong - """ - return cls._from_generated( - _SearchIndexerDataSource.from_dict(data, content_type=content_type, key_extractors=key_extractors) - ) - - -def pack_analyzer(analyzer): - if not analyzer: - return None - if isinstance(analyzer, (PatternAnalyzer, CustomAnalyzer)): - return analyzer._to_generated() # pylint:disable=protected-access - return analyzer - - -def unpack_analyzer(analyzer): - if not analyzer: - return None - if isinstance(analyzer, _PatternAnalyzer): - return PatternAnalyzer._from_generated(analyzer) # pylint:disable=protected-access - if isinstance(analyzer, _CustomAnalyzer): - return CustomAnalyzer._from_generated(analyzer) # pylint:disable=protected-access - return analyzer - - -class SearchIndexer(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Represents an indexer. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) - All required parameters must be populated in order to send to server. - :ivar name: The name of the indexer. Required. +class WordDelimiterTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.WordDelimiterTokenFilter"): + """Splits words into subwords and performs optional transformations on subword groups. This token + filter is implemented using Apache Lucene. + + :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes + or underscores, can only start and end with alphanumeric characters, and is limited to 128 + characters. Required. :vartype name: str - :ivar description: The description of the indexer. - :vartype description: str - :ivar data_source_name: The name of the datasource from which this indexer reads data. - Required. - :vartype data_source_name: str - :ivar skillset_name: The name of the skillset executing with this indexer. - :vartype skillset_name: str - :ivar target_index_name: The name of the index to which this indexer writes data. Required. - :vartype target_index_name: str - :ivar schedule: The schedule for this indexer. - :vartype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :ivar parameters: Parameters for indexer execution. - :vartype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :ivar field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :vartype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar output_field_mappings: Output field mappings are applied after enrichment and immediately - before indexing. - :vartype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :ivar is_disabled: A value indicating whether the indexer is disabled. Default is false. - :vartype is_disabled: bool - :ivar e_tag: The ETag of the indexer. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar cache: Adds caching to an enrichment pipeline to allow for incremental modification steps - without having to rebuild the index every time. - :vartype cache: ~azure.search.documents.indexes.models.SearchIndexerCache + :ivar generate_word_parts: A value indicating whether to generate part words. If set, causes + parts of words to be generated; for example "AzureSearch" becomes "Azure" "Search". Default is + true. + :vartype generate_word_parts: bool + :ivar generate_number_parts: A value indicating whether to generate number subwords. Default is + true. + :vartype generate_number_parts: bool + :ivar catenate_words: A value indicating whether maximum runs of word parts will be catenated. + For example, if this is set to true, "Azure-Search" becomes "AzureSearch". Default is false. + :vartype catenate_words: bool + :ivar catenate_numbers: A value indicating whether maximum runs of number parts will be + catenated. For example, if this is set to true, "1-2" becomes "12". Default is false. + :vartype catenate_numbers: bool + :ivar catenate_all: A value indicating whether all subword parts will be catenated. For + example, if this is set to true, "Azure-Search-1" becomes "AzureSearch1". Default is false. + :vartype catenate_all: bool + :ivar split_on_case_change: A value indicating whether to split words on caseChange. For + example, if this is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. + :vartype split_on_case_change: bool + :ivar preserve_original: A value indicating whether original words will be preserved and added + to the subword list. Default is false. + :vartype preserve_original: bool + :ivar split_on_numerics: A value indicating whether to split on numbers. For example, if this + is set to true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. + :vartype split_on_numerics: bool + :ivar stem_english_possessive: A value indicating whether to remove trailing "'s" for each + subword. Default is true. + :vartype stem_english_possessive: bool + :ivar protected_words: A list of tokens to protect from being delimited. + :vartype protected_words: list[str] + :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value + is "#Microsoft.Azure.Search.WordDelimiterTokenFilter". + :vartype odata_type: str """ + generate_word_parts: Optional[bool] = rest_field( + name="generateWordParts", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to generate part words. If set, causes parts of words to be + generated; for example \"AzureSearch\" becomes \"Azure\" \"Search\". Default is true.""" + generate_number_parts: Optional[bool] = rest_field( + name="generateNumberParts", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to generate number subwords. Default is true.""" + catenate_words: Optional[bool] = rest_field( + name="catenateWords", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether maximum runs of word parts will be catenated. For example, if this + is set to true, \"Azure-Search\" becomes \"AzureSearch\". Default is false.""" + catenate_numbers: Optional[bool] = rest_field( + name="catenateNumbers", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether maximum runs of number parts will be catenated. For example, if this + is set to true, \"1-2\" becomes \"12\". Default is false.""" + catenate_all: Optional[bool] = rest_field( + name="catenateAll", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether all subword parts will be catenated. For example, if this is set to + true, \"Azure-Search-1\" becomes \"AzureSearch1\". Default is false.""" + split_on_case_change: Optional[bool] = rest_field( + name="splitOnCaseChange", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to split words on caseChange. For example, if this is set to true, + \"AzureSearch\" becomes \"Azure\" \"Search\". Default is true.""" + preserve_original: Optional[bool] = rest_field( + name="preserveOriginal", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether original words will be preserved and added to the subword list. + Default is false.""" + split_on_numerics: Optional[bool] = rest_field( + name="splitOnNumerics", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to split on numbers. For example, if this is set to true, + \"Azure1Search\" becomes \"Azure\" \"1\" \"Search\". Default is true.""" + stem_english_possessive: Optional[bool] = rest_field( + name="stemEnglishPossessive", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to remove trailing \"'s\" for each subword. Default is true.""" + protected_words: Optional[list[str]] = rest_field( + name="protectedWords", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of tokens to protect from being delimited.""" + odata_type: Literal["#Microsoft.Azure.Search.WordDelimiterTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of token filter. Required. Default value is + \"#Microsoft.Azure.Search.WordDelimiterTokenFilter\".""" + + @overload def __init__( self, *, name: str, - data_source_name: str, - target_index_name: str, - description: Optional[str] = None, - skillset_name: Optional[str] = None, - schedule: Optional[IndexingSchedule] = None, - parameters: Optional[IndexingParameters] = None, - field_mappings: Optional[List[FieldMapping]] = None, - output_field_mappings: Optional[List[FieldMapping]] = None, - is_disabled: bool = False, - e_tag: Optional[str] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - cache: Optional[SearchIndexerCache] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of the indexer. Required. - :paramtype name: str - :keyword description: The description of the indexer. - :paramtype description: str - :keyword data_source_name: The name of the datasource from which this indexer reads data. - Required. - :paramtype data_source_name: str - :keyword skillset_name: The name of the skillset executing with this indexer. - :paramtype skillset_name: str - :keyword target_index_name: The name of the index to which this indexer writes data. Required. - :paramtype target_index_name: str - :keyword schedule: The schedule for this indexer. - :paramtype schedule: ~azure.search.documents.indexes.models.IndexingSchedule - :keyword parameters: Parameters for indexer execution. - :paramtype parameters: ~azure.search.documents.indexes.models.IndexingParameters - :keyword field_mappings: Defines mappings between fields in the data source and corresponding - target fields in the index. - :paramtype field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword output_field_mappings: Output field mappings are applied after enrichment and - immediately before indexing. - :paramtype output_field_mappings: list[~azure.search.documents.indexes.models.FieldMapping] - :keyword is_disabled: A value indicating whether the indexer is disabled. Default is false. - :paramtype is_disabled: bool - :keyword e_tag: The ETag of the indexer. - :paramtype e_tag: str - :keyword encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your indexer - definition (as well as indexer execution status) when you want full assurance that no one, not - even Microsoft, can decrypt them. Once you have encrypted your indexer definition, it will - always remain encrypted. The search service will ignore attempts to set this property to null. - You can change this property as needed if you want to rotate your encryption key; Your indexer - definition (and indexer execution status) will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :paramtype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :keyword cache: Adds caching to an enrichment pipeline to allow for incremental modification - steps without having to rebuild the index every time. - :paramtype cache: ~azure.search.documents.indexes.models.SearchIndexerCache - """ - super().__init__(**kwargs) - self.name = name - self.description = description - self.data_source_name = data_source_name - self.skillset_name = skillset_name - self.target_index_name = target_index_name - self.schedule = schedule - self.parameters = parameters - self.field_mappings = field_mappings - self.output_field_mappings = output_field_mappings - self.is_disabled = is_disabled - self.e_tag = e_tag - self.encryption_key = encryption_key - self.cache = cache - - def _to_generated(self): - return _SearchIndexer( - name=self.name, - description=self.description, - data_source_name=self.data_source_name, - skillset_name=self.skillset_name, - target_index_name=self.target_index_name, - schedule=self.schedule, - parameters=self.parameters, - field_mappings=self.field_mappings, - output_field_mappings=self.output_field_mappings, - is_disabled=self.is_disabled, - e_tag=self.e_tag, - encryption_key=( - self.encryption_key._to_generated() if self.encryption_key else None # pylint:disable=protected-access - ), - cache=self.cache, - ) - - @classmethod - def _from_generated(cls, search_indexer) -> Optional[Self]: - if not search_indexer: - return None - return cls( - name=search_indexer.name, - description=search_indexer.description, - data_source_name=search_indexer.data_source_name, - skillset_name=search_indexer.skillset_name, - target_index_name=search_indexer.target_index_name, - schedule=search_indexer.schedule, - parameters=search_indexer.parameters, - field_mappings=search_indexer.field_mappings, - output_field_mappings=search_indexer.output_field_mappings, - is_disabled=search_indexer.is_disabled, - e_tag=search_indexer.e_tag, - # pylint:disable=protected-access - encryption_key=SearchResourceEncryptionKey._from_generated(search_indexer.encryption_key), - cache=search_indexer.cache, - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: - """Return the JSON that would be sent to server from this model. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore - """Parse a str using the RestAPI syntax and return a SearchIndexer instance. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: A SearchIndexer instance - :rtype: SearchIndexer - :raises DeserializationError: if something went wrong - """ - return cls._from_generated(_SearchIndexer.deserialize(data, content_type=content_type)) + generate_word_parts: Optional[bool] = None, + generate_number_parts: Optional[bool] = None, + catenate_words: Optional[bool] = None, + catenate_numbers: Optional[bool] = None, + catenate_all: Optional[bool] = None, + split_on_case_change: Optional[bool] = None, + preserve_original: Optional[bool] = None, + split_on_numerics: Optional[bool] = None, + stem_english_possessive: Optional[bool] = None, + protected_words: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Azure.Search.WordDelimiterTokenFilter" # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py new file mode 100644 index 000000000000..6b1532241601 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataSourcesOperations # type: ignore +from ._operations import IndexersOperations # type: ignore +from ._operations import SkillsetsOperations # type: ignore +from ._operations import SynonymMapsOperations # type: ignore +from ._operations import IndexesOperations # type: ignore +from ._operations import AliasesOperations # type: ignore +from ._operations import AgentsOperations # type: ignore +from ._operations import SourcesOperations # type: ignore +from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataSourcesOperations", + "IndexersOperations", + "SkillsetsOperations", + "SynonymMapsOperations", + "IndexesOperations", + "AliasesOperations", + "AgentsOperations", + "SourcesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py new file mode 100644 index 000000000000..a4892dc4f293 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py @@ -0,0 +1,6807 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core import MatchConditions, PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceModifiedError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1 +from ... import models as _models2 +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match +from ..._validation import api_version_validation +from .._configuration import SearchIndexClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_data_sources_create_or_update_request( # pylint: disable=name-too-long + data_source_name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/datasources('{dataSourceName}')" + path_format_arguments = { + "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_sources_delete_request( + data_source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/datasources('{dataSourceName}')" + path_format_arguments = { + "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_sources_get_request(data_source_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/datasources('{dataSourceName}')" + path_format_arguments = { + "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_sources_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/datasources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_sources_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/datasources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_reset_request(indexer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/indexers('{indexerName}')/search.reset" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_resync_request(indexer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/indexers('{indexerName}')/search.resync" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_reset_docs_request( + indexer_name: str, *, overwrite: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/indexers('{indexerName}')/search.resetdocs" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if overwrite is not None: + _params["overwrite"] = _SERIALIZER.query("overwrite", overwrite, "bool") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_run_request(indexer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/indexers('{indexerName}')/search.run" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_create_or_update_request( + indexer_name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexers('{indexerName}')" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + if disable_cache_reprocessing_change_detection is not None: + _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( + "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + ) + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_delete_request( + indexer_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/indexers('{indexerName}')" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_get_request(indexer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexers('{indexerName}')" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexers" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexers" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexers_get_status_request(indexer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexers('{indexerName}')/search.status" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_skillsets_create_or_update_request( + skillset_name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + if disable_cache_reprocessing_change_detection is not None: + _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( + "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + ) + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_skillsets_delete_request( + skillset_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_skillsets_get_request(skillset_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_skillsets_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_skillsets_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_skillsets_reset_skills_request(skillset_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/skillsets('{skillsetName}')/search.resetskills" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_synonym_maps_create_or_update_request( # pylint: disable=name-too-long + synonym_map_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/synonymmaps('{synonymMapName}')" + path_format_arguments = { + "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_synonym_maps_delete_request( + synonym_map_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/synonymmaps('{synonymMapName}')" + path_format_arguments = { + "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_synonym_maps_get_request(synonym_map_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/synonymmaps('{synonymMapName}')" + path_format_arguments = { + "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_synonym_maps_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/synonymmaps" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_synonym_maps_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/synonymmaps" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_create_or_update_request( + index_name: str, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if allow_index_downtime is not None: + _params["allowIndexDowntime"] = _SERIALIZER.query("allow_index_downtime", allow_index_downtime, "bool") + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_delete_request( + index_name: str, + *, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/indexes('{indexName}')" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_get_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_get_statistics_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/search.stats" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_indexes_analyze_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/search.analyze" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aliases_create_or_update_request( + alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aliases_delete_request( + alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aliases_get_request(alias_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aliases_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/aliases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aliases_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/aliases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agents_create_or_update_request( + agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/agents('{agentName}')" + path_format_arguments = { + "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agents_delete_request( + agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/agents('{agentName}')" + path_format_arguments = { + "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agents_get_request(agent_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/agents('{agentName}')" + path_format_arguments = { + "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agents_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/agents" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_agents_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/agents" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sources_create_or_update_request( + source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgesources('{sourceName}')" + path_format_arguments = { + "sourceName": _SERIALIZER.url("source_name", source_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sources_delete_request( + source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/knowledgesources('{sourceName}')" + path_format_arguments = { + "sourceName": _SERIALIZER.url("source_name", source_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sources_get_request(source_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgesources('{sourceName}')" + path_format_arguments = { + "sourceName": _SERIALIZER.url("source_name", source_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sources_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgesources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sources_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgesources" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_service_statistics_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/servicestats" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_get_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexstats" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DataSourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`data_sources` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + data_source_name: str, + data_source: _models1.SearchIndexerDataSource, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + data_source_name: str, + data_source: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + data_source_name: str, + data_source: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update( + self, + data_source_name: str, + data_source: Union[_models1.SearchIndexerDataSource, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource or updates a datasource if it already exists. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Is one of the + following types: SearchIndexerDataSource, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or + IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerDataSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source, (IOBase, bytes)): + _content = data_source + else: + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_data_sources_create_or_update_request( + data_source_name=data_source_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerDataSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + data_source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a datasource. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_data_sources_delete_request( + data_source_name=data_source_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get(self, data_source_name: str, **kwargs: Any) -> _models1.SearchIndexerDataSource: + """Retrieves a datasource definition. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerDataSource] = kwargs.pop("cls", None) + + _request = build_data_sources_get_request( + data_source_name=data_source_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerDataSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListDataSourcesResult: + """Lists all datasources available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.ListDataSourcesResult] = kwargs.pop("cls", None) + + _request = build_data_sources_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.ListDataSourcesResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, data_source: _models1.SearchIndexerDataSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, data_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, data_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, data_source: Union[_models1.SearchIndexerDataSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexerDataSource: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Is one of the following types: + SearchIndexerDataSource, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or + IO[bytes] + :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerDataSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(data_source, (IOBase, bytes)): + _content = data_source + else: + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_data_sources_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerDataSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class IndexersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`indexers` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def reset(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Resets the change tracking state associated with an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_reset_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Resync selective options from the datasource to be re-ingested by the indexer.". + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_resync_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[_models1.DocumentKeysOrIds] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[JSON] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: JSON + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def reset_docs( + self, + indexer_name: str, + keys_or_ids: Optional[IO[bytes]] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def reset_docs( # pylint: disable=inconsistent-return-statements + self, + indexer_name: str, + keys_or_ids: Optional[Union[_models1.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + *, + overwrite: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, + IO[bytes] Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or + IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type = content_type if keys_or_ids else None + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" if keys_or_ids else None + _content = None + if isinstance(keys_or_ids, (IOBase, bytes)): + _content = keys_or_ids + else: + if keys_or_ids is not None: + _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + else: + _content = None + + _request = build_indexers_reset_docs_request( + indexer_name=indexer_name, + overwrite=overwrite, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def run(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Runs an indexer on-demand. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_run_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + indexer_name: str, + indexer: _models1.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + indexer_name: str, + indexer: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + indexer_name: str, + indexer: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + params_added_on={ + "2025-08-01-preview": [ + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", + ] + }, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update( + self, + indexer_name: str, + indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Is one of the following + types: SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexers_create_or_update_request( + indexer_name=indexer_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + indexer_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexers_delete_request( + indexer_name=indexer_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexer: + """Retrieves an indexer definition. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + _request = build_indexers_get_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListIndexersResult: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListIndexersResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.ListIndexersResult] = kwargs.pop("cls", None) + + _request = build_indexers_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.ListIndexersResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, indexer: _models1.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create(self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Required. + :type indexer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create(self, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Is one of the following types: + SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexers_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_status(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexerStatus: + """Returns the current status and execution history of an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerStatus] = kwargs.pop("cls", None) + + _request = build_indexers_get_status_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SkillsetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`skillsets` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + skillset_name: str, + skillset: _models1.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + skillset_name: str, + skillset: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + skillset_name: str, + skillset: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + params_added_on={ + "2025-08-01-preview": [ + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", + ] + }, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update( + self, + skillset_name: str, + skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_skillsets_create_or_update_request( + skillset_name=skillset_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + skillset_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_skillsets_delete_request( + skillset_name=skillset_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get(self, skillset_name: str, **kwargs: Any) -> _models1.SearchIndexerSkillset: + """Retrieves a skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + + _request = build_skillsets_get_request( + skillset_name=skillset_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSkillsetsResult: + """List all skillsets in a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.ListSkillsetsResult] = kwargs.pop("cls", None) + + _request = build_skillsets_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.ListSkillsetsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, skillset: _models1.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. + + :param skillset: The skillset containing one or more skills to create in a search service. Is + one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + IO[bytes] + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skillset, (IOBase, bytes)): + _content = skillset + else: + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_skillsets_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def reset_skills( + self, + skillset_name: str, + skill_names: _models1.SkillNames, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def reset_skills( + self, skillset_name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def reset_skills( + self, skillset_name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def reset_skills( # pylint: disable=inconsistent-return-statements + self, skillset_name: str, skill_names: Union[_models1.SkillNames, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skill_names, (IOBase, bytes)): + _content = skill_names + else: + _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_skillsets_reset_skills_request( + skillset_name=skillset_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class SynonymMapsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`synonym_maps` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + synonym_map_name: str, + synonym_map: _models1.SynonymMap, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + synonym_map_name: str, + synonym_map: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + synonym_map_name: str, + synonym_map: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + synonym_map_name: str, + synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Is one of the + following types: SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_synonym_maps_create_or_update_request( + synonym_map_name=synonym_map_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + synonym_map_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a synonym map. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_synonym_maps_delete_request( + synonym_map_name=synonym_map_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get(self, synonym_map_name: str, **kwargs: Any) -> _models1.SynonymMap: + """Retrieves a synonym map definition. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + + _request = build_synonym_maps_get_request( + synonym_map_name=synonym_map_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSynonymMapsResult: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.ListSynonymMapsResult] = kwargs.pop("cls", None) + + _request = build_synonym_maps_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.ListSynonymMapsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, synonym_map: _models1.SynonymMap, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create(self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwargs: Any) -> _models1.SynonymMap: + """Creates a new synonym map. + + :param synonym_map: The definition of the synonym map to create. Is one of the following types: + SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map + else: + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_synonym_maps_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SynonymMap, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class IndexesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`indexes` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + index_name: str, + index: _models1.SearchIndex, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + index_name: str, + index: JSON, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: JSON + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + index_name: str, + index: IO[bytes], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + index_name: str, + index: Union[_models1.SearchIndex, JSON, IO[bytes]], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_create_or_update_request( + index_name=index_name, + allow_index_downtime=allow_index_downtime, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + index_name: str, + *, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search index and all the documents it contains. This operation is permanent, with no + recovery option. Make sure you have a master copy of your index definition, data ingestion + code, and a backup of the primary data source in case you need to re-build the index. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_indexes_delete_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models1.SearchIndex: + """Retrieves an index definition. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + _request = build_indexes_get_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SearchIndex"]: + """Lists all indexes available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: An iterator like instance of SearchIndex + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models1.SearchIndex]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_indexes_list_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models1.SearchIndex], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create( + self, index: _models1.SearchIndex, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create(self, index: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_statistics( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models1.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.GetIndexStatisticsResult] = kwargs.pop("cls", None) + + _request = build_indexes_get_statistics_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.GetIndexStatisticsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def analyze( + self, + index_name: str, + request: _models1.AnalyzeRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def analyze( + self, + index_name: str, + request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def analyze( + self, + index_name: str, + request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def analyze( + self, + index_name: str, + request: Union[_models1.AnalyzeRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. + + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Is one of the following + types: AnalyzeRequest, JSON, IO[bytes] Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.AnalyzeResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_analyze_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.AnalyzeResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class AliasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`aliases` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + alias_name: str, + alias: _models1.SearchAlias, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + alias_name: str, + alias: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + alias_name: str, + alias: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": [ + "api_version", + "prefer", + "client_request_id", + "alias_name", + "content_type", + "accept", + "etag", + "match_condition", + ] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update( + self, + alias_name: str, + alias: Union[_models1.SearchAlias, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_aliases_create_or_update_request( + alias_name=alias_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "etag", "match_condition"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def delete( # pylint: disable=inconsistent-return-statements + self, + alias_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_aliases_delete_request( + alias_name=alias_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get(self, alias_name: str, **kwargs: Any) -> _models1.SearchAlias: + """Retrieves an alias definition. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + + _request = build_aliases_get_request( + alias_name=alias_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def list(self, **kwargs: Any) -> ItemPaged["_models1.SearchAlias"]: + """Lists all aliases available for a search service. + + :return: An iterator like instance of SearchAlias + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models1.SearchAlias]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_aliases_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models1.SearchAlias], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create( + self, alias: _models1.SearchAlias, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create(self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def create(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchAlias: + """Creates a new search alias. + + :param alias: The definition of the alias to create. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_aliases_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchAlias, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class AgentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`agents` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + agent_name: str, + knowledge_agent: _models1.KnowledgeAgent, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + agent_name: str, + knowledge_agent: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + agent_name: str, + knowledge_agent: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": [ + "api_version", + "prefer", + "client_request_id", + "agent_name", + "content_type", + "accept", + "etag", + "match_condition", + ] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update( + self, + agent_name: str, + knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Is one of the + following types: KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or + IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent + else: + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agents_create_or_update_request( + agent_name=agent_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "etag", "match_condition"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def delete( # pylint: disable=inconsistent-return-statements + self, + agent_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_agents_delete_request( + agent_name=agent_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: + """Retrieves an agent definition. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + + _request = build_agents_get_request( + agent_name=agent_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def list(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: + """Lists all agents available for a search service. + + :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) + + _request = build_agents_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.ListKnowledgeAgentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, knowledge_agent: _models1.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def create( + self, knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. + + :param knowledge_agent: The definition of the agent to create. Is one of the following types: + KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or + IO[bytes] + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent + else: + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_agents_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchIndexClient`'s + :attr:`sources` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + source_name: str, + knowledge_source: _models1.KnowledgeSource, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + source_name: str, + knowledge_source: JSON, + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + source_name: str, + knowledge_source: IO[bytes], + *, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": [ + "api_version", + "prefer", + "client_request_id", + "source_name", + "content_type", + "accept", + "etag", + "match_condition", + ] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update( + self, + source_name: str, + knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Is one of + the following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_sources_create_or_update_request( + source_name=source_name, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={ + "2025-08-01-preview": ["api_version", "client_request_id", "source_name", "etag", "match_condition"] + }, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def delete( # pylint: disable=inconsistent-return-statements + self, + source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes an existing knowledge source. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_sources_delete_request( + source_name=source_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "source_name", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get(self, source_name: str, **kwargs: Any) -> _models1.KnowledgeSource: + """Retrieves a knowledge source definition. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + + _request = build_sources_get_request( + source_name=source_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def list(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: + """Lists all knowledge sources available for a search service. + + :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) + + _request = build_sources_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.ListKnowledgeSourcesResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, knowledge_source: _models1.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def create( + self, knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Is one of the + following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_sources_create_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class _SearchIndexClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchIndexClientConfiguration] +): + + @distributed_trace + def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatistics: + """Gets service level statistics for a search service. + + :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchServiceStatistics] = kwargs.pop("cls", None) + + _request = build_search_index_get_service_statistics_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchServiceStatistics, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: + """Retrieves a summary of statistics for all indexes in the search service. + + :return: An iterator like instance of IndexStatisticsSummary + :rtype: + ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models1.IndexStatisticsSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_get_index_stats_summary_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models1.IndexStatisticsSummary], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/__init__.py similarity index 65% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/__init__.py index b24a07c02d65..f721cfb1ed80 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,7 +12,10 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._search_index_client import SearchIndexClient # type: ignore +from ._client import KnowledgeBaseRetrievalClient # type: ignore +from .._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all @@ -20,7 +25,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "SearchIndexClient", + "KnowledgeBaseRetrievalClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_knowledge_agent_retrieval_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py similarity index 65% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_knowledge_agent_retrieval_client.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py index 799ecddcb875..e701aa5d5822 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_knowledge_agent_retrieval_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py @@ -1,43 +1,48 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import PipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import KnowledgeAgentRetrievalClientConfiguration -from ._utils.serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer +from ._configuration import KnowledgeBaseRetrievalClientConfiguration from .operations import KnowledgeRetrievalOperations +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class KnowledgeAgentRetrievalClient: - """Client that can be used to query an agent. + +class KnowledgeBaseRetrievalClient: + """KnowledgeBaseRetrievalClient. :ivar knowledge_retrieval: KnowledgeRetrievalOperations operations - :vartype knowledge_retrieval: - azure.search.documents.agent.operations.KnowledgeRetrievalOperations - :param endpoint: The endpoint URL of the search service. Required. + :vartype knowledge_retrieval: azure.search.documents.operations.KnowledgeRetrievalOperations + :param endpoint: Service host. Required. :type endpoint: str - :param agent_name: The name of the agent. Required. - :type agent_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, agent_name: str, **kwargs: Any - ) -> None: - _endpoint = "{endpoint}/agents('{agentName}')" - self._config = KnowledgeAgentRetrievalClientConfiguration(endpoint=endpoint, agent_name=agent_name, **kwargs) + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = KnowledgeBaseRetrievalClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -58,21 +63,20 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.knowledge_retrieval = KnowledgeRetrievalOperations( self._client, self._config, self._serialize, self._deserialize ) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -87,7 +91,6 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "agentName": self._serialize.url("self._config.agent_name", self._config.agent_name, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_configuration.py new file mode 100644 index 000000000000..425408a1c073 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class KnowledgeBaseRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for KnowledgeBaseRetrievalClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/models/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/__init__.py similarity index 52% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_utils/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/__init__.py index f986b371549e..8026245c2abc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_utils/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/__init__.py @@ -1,4 +1,6 @@ # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/model_base.py @@ -0,0 +1,1237 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + return getattr(self._type, "args", [None])[0] + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + item = obj.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + return _deserialize(self._type, _serialize(item, self._format), rf=self) + + def __set__(self, obj: Model, value) -> None: + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/serialization.py similarity index 99% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_utils/serialization.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/serialization.py index 003e1c89fb35..45a3e44e45cb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/_utils/serialization.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/serialization.py @@ -1,7 +1,9 @@ # pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -785,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/__init__.py similarity index 68% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/__init__.py index 79e8ad096465..e682791dd38b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._knowledge_agent_retrieval_client import KnowledgeAgentRetrievalClient # type: ignore +from ._client import KnowledgeBaseRetrievalClient # type: ignore try: from ._patch import __all__ as _patch_all @@ -20,7 +22,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "KnowledgeAgentRetrievalClient", + "KnowledgeBaseRetrievalClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_knowledge_agent_retrieval_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py similarity index 67% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_knowledge_agent_retrieval_client.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py index 40d68fb6e571..f6cc4b139bb1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/_knowledge_agent_retrieval_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py @@ -1,43 +1,51 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models -from .._utils.serialization import Deserializer, Serializer -from ._configuration import KnowledgeAgentRetrievalClientConfiguration +from ..._utils.serialization import Deserializer, Serializer +from ._configuration import KnowledgeBaseRetrievalClientConfiguration from .operations import KnowledgeRetrievalOperations +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class KnowledgeAgentRetrievalClient: - """Client that can be used to query an agent. + +class KnowledgeBaseRetrievalClient: + """KnowledgeBaseRetrievalClient. :ivar knowledge_retrieval: KnowledgeRetrievalOperations operations :vartype knowledge_retrieval: - azure.search.documents.agent.aio.operations.KnowledgeRetrievalOperations - :param endpoint: The endpoint URL of the search service. Required. + azure.search.documents.aio.operations.KnowledgeRetrievalOperations + :param endpoint: Service host. Required. :type endpoint: str - :param agent_name: The name of the agent. Required. - :type agent_name: str - :keyword api_version: Api Version. Default value is "2025-08-01-preview". Note that overriding - this default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, agent_name: str, **kwargs: Any + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - _endpoint = "{endpoint}/agents('{agentName}')" - self._config = KnowledgeAgentRetrievalClientConfiguration(endpoint=endpoint, agent_name=agent_name, **kwargs) + _endpoint = "{endpoint}" + self._config = KnowledgeBaseRetrievalClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -58,15 +66,14 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.knowledge_retrieval = KnowledgeRetrievalOperations( self._client, self._config, self._serialize, self._deserialize ) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -74,7 +81,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -89,7 +96,6 @@ def _send_request( request_copy = deepcopy(request) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "agentName": self._serialize.url("self._config.agent_name", self._config.agent_name, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_configuration.py new file mode 100644 index 000000000000..ec28807286a4 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_configuration.py @@ -0,0 +1,74 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING, Union + +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from ..._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class KnowledgeBaseRetrievalClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for KnowledgeBaseRetrievalClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/__init__.py similarity index 70% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/__init__.py index ee2a3f9ac8bb..48bd23b4f6a7 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._knowledge_retrieval_operations import KnowledgeRetrievalOperations # type: ignore +from ._operations import KnowledgeRetrievalOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py new file mode 100644 index 000000000000..e0ff63ac5b1e --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py @@ -0,0 +1,248 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2 +from ...._utils.model_base import SdkJSONEncoder, _deserialize +from ...._utils.serialization import Deserializer, Serializer +from ...._validation import api_version_validation +from ...operations._operations import build_knowledge_retrieval_retrieve_request +from .._configuration import KnowledgeBaseRetrievalClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class KnowledgeRetrievalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.aio.KnowledgeBaseRetrievalClient`'s + :attr:`knowledge_retrieval` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: KnowledgeBaseRetrievalClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: _models2.KnowledgeBaseRetrievalRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: + ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2025-11-01-preview", + params_added_on={ + "2025-11-01-preview": [ + "api_version", + "knowledge_base_name", + "query_source_authorization", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2025-11-01-preview"], + ) + async def retrieve( + self, + knowledge_base_name: str, + retrieval_request: Union[_models2.KnowledgeBaseRetrievalRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models2.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Is one of the following types: + KnowledgeBaseRetrievalRequest, JSON, IO[bytes] Required. + :type retrieval_request: + ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeBaseRetrievalResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(retrieval_request, (IOBase, bytes)): + _content = retrieval_request + else: + _content = json.dumps(retrieval_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_retrieval_retrieve_request( + knowledge_base_name=knowledge_base_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeBaseRetrievalResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py new file mode 100644 index 000000000000..f800324958aa --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py @@ -0,0 +1,106 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AzureBlobKnowledgeSourceParams, + IndexedOneLakeKnowledgeSourceParams, + IndexedSharePointKnowledgeSourceParams, + KnowledgeBaseActivityRecord, + KnowledgeBaseAgenticReasoningActivityRecord, + KnowledgeBaseAzureBlobReference, + KnowledgeBaseErrorAdditionalInfo, + KnowledgeBaseErrorDetail, + KnowledgeBaseImageContent, + KnowledgeBaseIndexedOneLakeReference, + KnowledgeBaseIndexedSharePointReference, + KnowledgeBaseMessage, + KnowledgeBaseMessageContent, + KnowledgeBaseMessageImageContent, + KnowledgeBaseMessageTextContent, + KnowledgeBaseModelAnswerSynthesisActivityRecord, + KnowledgeBaseModelQueryPlanningActivityRecord, + KnowledgeBaseReference, + KnowledgeBaseRemoteSharePointReference, + KnowledgeBaseRetrievalRequest, + KnowledgeBaseRetrievalResponse, + KnowledgeBaseSearchIndexReference, + KnowledgeBaseWebReference, + KnowledgeRetrievalHighReasoningEffort, + KnowledgeRetrievalIntent, + KnowledgeRetrievalLowReasoningEffort, + KnowledgeRetrievalMediumReasoningEffort, + KnowledgeRetrievalMinimalReasoningEffort, + KnowledgeRetrievalReasoningEffort, + KnowledgeRetrievalSemanticIntent, + KnowledgeSourceParams, + RemoteSharePointKnowledgeSourceParams, + SearchIndexKnowledgeSourceParams, + SharePointSensitivityLabelInfo, + WebKnowledgeSourceParams, +) + +from ._enums import ( # type: ignore + KnowledgeBaseMessageContentType, + KnowledgeRetrievalIntentType, + KnowledgeRetrievalOutputMode, + KnowledgeRetrievalReasoningEffortKind, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureBlobKnowledgeSourceParams", + "IndexedOneLakeKnowledgeSourceParams", + "IndexedSharePointKnowledgeSourceParams", + "KnowledgeBaseActivityRecord", + "KnowledgeBaseAgenticReasoningActivityRecord", + "KnowledgeBaseAzureBlobReference", + "KnowledgeBaseErrorAdditionalInfo", + "KnowledgeBaseErrorDetail", + "KnowledgeBaseImageContent", + "KnowledgeBaseIndexedOneLakeReference", + "KnowledgeBaseIndexedSharePointReference", + "KnowledgeBaseMessage", + "KnowledgeBaseMessageContent", + "KnowledgeBaseMessageImageContent", + "KnowledgeBaseMessageTextContent", + "KnowledgeBaseModelAnswerSynthesisActivityRecord", + "KnowledgeBaseModelQueryPlanningActivityRecord", + "KnowledgeBaseReference", + "KnowledgeBaseRemoteSharePointReference", + "KnowledgeBaseRetrievalRequest", + "KnowledgeBaseRetrievalResponse", + "KnowledgeBaseSearchIndexReference", + "KnowledgeBaseWebReference", + "KnowledgeRetrievalHighReasoningEffort", + "KnowledgeRetrievalIntent", + "KnowledgeRetrievalLowReasoningEffort", + "KnowledgeRetrievalMediumReasoningEffort", + "KnowledgeRetrievalMinimalReasoningEffort", + "KnowledgeRetrievalReasoningEffort", + "KnowledgeRetrievalSemanticIntent", + "KnowledgeSourceParams", + "RemoteSharePointKnowledgeSourceParams", + "SearchIndexKnowledgeSourceParams", + "SharePointSensitivityLabelInfo", + "WebKnowledgeSourceParams", + "KnowledgeBaseMessageContentType", + "KnowledgeRetrievalIntentType", + "KnowledgeRetrievalOutputMode", + "KnowledgeRetrievalReasoningEffortKind", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py new file mode 100644 index 000000000000..31ccafa2e2fb --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class KnowledgeBaseMessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of message content.""" + + TEXT = "text" + """Text message content kind.""" + IMAGE = "image" + """Image message content kind.""" + + +class KnowledgeRetrievalIntentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of knowledge base configuration to use.""" + + SEMANTIC = "semantic" + """A natural language semantic query intent.""" + + +class KnowledgeRetrievalOutputMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The output configuration for this retrieval.""" + + EXTRACTIVE_DATA = "extractiveData" + """Return data from the knowledge sources directly without generative alteration.""" + ANSWER_SYNTHESIS = "answerSynthesis" + """Synthesize an answer for the response payload.""" + + +class KnowledgeRetrievalReasoningEffortKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The amount of effort to use during retrieval.""" + + MINIMAL = "minimal" + """Does not perform any source selections, any query planning, or any iterative search.""" + LOW = "low" + """Use low reasoning during retrieval.""" + MEDIUM = "medium" + """Use a moderate amount of reasoning during retrieval.""" + HIGH = "high" + """Use a high amount of reasoning during retrieval.""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py new file mode 100644 index 000000000000..52e7361e8888 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py @@ -0,0 +1,1627 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from ..._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ...indexes.models._enums import KnowledgeSourceKind +from ._enums import KnowledgeBaseMessageContentType, KnowledgeRetrievalIntentType, KnowledgeRetrievalReasoningEffortKind + +if TYPE_CHECKING: + from .. import models as _models + + +class KnowledgeSourceParams(_Model): + """Base type for knowledge source runtime parameters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureBlobKnowledgeSourceParams, IndexedOneLakeKnowledgeSourceParams, + IndexedSharePointKnowledgeSourceParams, RemoteSharePointKnowledgeSourceParams, + SearchIndexKnowledgeSourceParams, WebKnowledgeSourceParams + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", + "azureBlob", "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind + """ + + __mapping__: dict[str, _Model] = {} + knowledge_source_name: str = rest_field( + name="knowledgeSourceName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the index the params apply to. Required.""" + include_references: Optional[bool] = rest_field( + name="includeReferences", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether references should be included for data retrieved from this source.""" + include_reference_source_data: Optional[bool] = rest_field( + name="includeReferenceSourceData", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether references should include the structured data obtained during retrieval in + their payload.""" + always_query_source: Optional[bool] = rest_field( + name="alwaysQuerySource", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates that this knowledge source should bypass source selection and always be queried at + retrieval time.""" + reranker_threshold: Optional[float] = rest_field( + name="rerankerThreshold", visibility=["read", "create", "update", "delete", "query"] + ) + """The reranker threshold all retrieved documents must meet to be included in the response.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The type of the knowledge source. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + kind: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AzureBlobKnowledgeSourceParams(KnowledgeSourceParams, discriminator="azureBlob"): + """Specifies runtime parameters for a azure blob knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that read and ingest data + from Azure Blob Storage to a Search Index. + :vartype kind: str or ~azure.search.documents.indexes.models.AZURE_BLOB + """ + + kind: Literal[KnowledgeSourceKind.AZURE_BLOB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that read and ingest data from Azure Blob + Storage to a Search Index.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.AZURE_BLOB # type: ignore + + +class IndexedOneLakeKnowledgeSourceParams(KnowledgeSourceParams, discriminator="indexedOneLake"): + """Specifies runtime parameters for a indexed OneLake knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from indexed + OneLake. + :vartype kind: str or ~azure.search.documents.indexes.models.INDEXED_ONE_LAKE + """ + + kind: Literal[KnowledgeSourceKind.INDEXED_ONE_LAKE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from indexed OneLake.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.INDEXED_ONE_LAKE # type: ignore + + +class IndexedSharePointKnowledgeSourceParams(KnowledgeSourceParams, discriminator="indexedSharePoint"): + """Specifies runtime parameters for a indexed SharePoint knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from indexed + SharePoint. + :vartype kind: str or ~azure.search.documents.indexes.models.INDEXED_SHARE_POINT + """ + + kind: Literal[KnowledgeSourceKind.INDEXED_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from indexed SharePoint.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.INDEXED_SHARE_POINT # type: ignore + + +class KnowledgeBaseActivityRecord(_Model): + """Base type for activity records. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseAgenticReasoningActivityRecord, KnowledgeBaseModelAnswerSynthesisActivityRecord, + KnowledgeBaseModelQueryPlanningActivityRecord + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar type: The type of the activity record. Required. Default value is None. + :vartype type: str + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail + """ + + __mapping__: dict[str, _Model] = {} + id: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the activity record. Required.""" + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the activity record. Required. Default value is None.""" + elapsed_ms: Optional[int] = rest_field(name="elapsedMs", visibility=["read", "create", "update", "delete", "query"]) + """The elapsed time in milliseconds for the retrieval activity.""" + error: Optional["_models.KnowledgeBaseErrorDetail"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The error detail explaining why the operation failed. This property is only included when the + activity does not succeed.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + type: str, + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseAgenticReasoningActivityRecord( + KnowledgeBaseActivityRecord, discriminator="agenticReasoning" +): # pylint: disable=name-too-long + """Represents an agentic reasoning activity record. + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail + :ivar type: The discriminator value. Required. Default value is "agenticReasoning". + :vartype type: str + :ivar reasoning_tokens: The number of input tokens for agentic reasoning. + :vartype reasoning_tokens: int + :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. + :vartype retrieval_reasoning_effort: + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffort + """ + + type: Literal["agenticReasoning"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"agenticReasoning\".""" + reasoning_tokens: Optional[int] = rest_field( + name="reasoningTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of input tokens for agentic reasoning.""" + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = rest_field( + name="retrievalReasoningEffort", visibility=["read", "create", "update", "delete", "query"] + ) + """The retrieval reasoning effort configuration.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + reasoning_tokens: Optional[int] = None, + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "agenticReasoning" # type: ignore + + +class KnowledgeBaseReference(_Model): + """Base type for references. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseAzureBlobReference, KnowledgeBaseIndexedOneLakeReference, + KnowledgeBaseIndexedSharePointReference, KnowledgeBaseRemoteSharePointReference, + KnowledgeBaseSearchIndexReference, KnowledgeBaseWebReference + + :ivar type: The type of the reference. Required. Default value is None. + :vartype type: str + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the reference. Required. Default value is None.""" + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the reference. Required.""" + activity_source: int = rest_field(name="activitySource", visibility=["read", "create", "update", "delete", "query"]) + """The source activity ID for the reference. Required.""" + source_data: Optional[dict[str, str]] = rest_field( + name="sourceData", visibility=["read", "create", "update", "delete", "query"] + ) + """The source data for the reference.""" + reranker_score: Optional[float] = rest_field( + name="rerankerScore", visibility=["read", "create", "update", "delete", "query"] + ) + """The reranker score for the document reference.""" + + @overload + def __init__( + self, + *, + type: str, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseAzureBlobReference(KnowledgeBaseReference, discriminator="azureBlob"): + """Represents an Azure Blob Storage document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Default value is "azureBlob". + :vartype type: str + :ivar blob_url: The blob URL for the reference. + :vartype blob_url: str + """ + + type: Literal["azureBlob"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"azureBlob\".""" + blob_url: Optional[str] = rest_field(name="blobUrl", visibility=["read", "create", "update", "delete", "query"]) + """The blob URL for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + blob_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "azureBlob" # type: ignore + + +class KnowledgeBaseErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: dict[str, str] + """ + + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The additional info type.""" + info: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The additional info.""" + + @overload + def __init__( + self, + *, + type: Optional[str] = None, + info: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseErrorDetail(_Model): + """The error details. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error target.""" + details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The error details.""" + additional_info: Optional[list["_models.KnowledgeBaseErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read", "create", "update", "delete", "query"] + ) + """The error additional info.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + message: Optional[str] = None, + target: Optional[str] = None, + details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = None, + additional_info: Optional[list["_models.KnowledgeBaseErrorAdditionalInfo"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseImageContent(_Model): + """Image content. + + :ivar url: The url of the image. Required. + :vartype url: str + """ + + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url of the image. Required.""" + + @overload + def __init__( + self, + *, + url: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseIndexedOneLakeReference(KnowledgeBaseReference, discriminator="indexedOneLake"): + """Represents an indexed OneLake document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Default value is "indexedOneLake". + :vartype type: str + :ivar doc_url: The document URL for the reference. + :vartype doc_url: str + """ + + type: Literal["indexedOneLake"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"indexedOneLake\".""" + doc_url: Optional[str] = rest_field(name="docUrl", visibility=["read", "create", "update", "delete", "query"]) + """The document URL for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + doc_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "indexedOneLake" # type: ignore + + +class KnowledgeBaseIndexedSharePointReference(KnowledgeBaseReference, discriminator="indexedSharePoint"): + """Represents an indexed SharePoint document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Default value is "indexedSharePoint". + :vartype type: str + :ivar doc_url: The document URL for the reference. + :vartype doc_url: str + """ + + type: Literal["indexedSharePoint"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"indexedSharePoint\".""" + doc_url: Optional[str] = rest_field(name="docUrl", visibility=["read", "create", "update", "delete", "query"]) + """The document URL for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + doc_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "indexedSharePoint" # type: ignore + + +class KnowledgeBaseMessage(_Model): + """The natural language message style object. + + :ivar role: The role of the tool response. + :vartype role: str + :ivar content: The content of the message. Required. + :vartype content: + list[~azure.search.documents.knowledgebase.models.KnowledgeBaseMessageContent] + """ + + role: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The role of the tool response.""" + content: list["_models.KnowledgeBaseMessageContent"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The content of the message. Required.""" + + @overload + def __init__( + self, + *, + content: list["_models.KnowledgeBaseMessageContent"], + role: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseMessageContent(_Model): + """Specifies the type of the message content. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseMessageImageContent, KnowledgeBaseMessageTextContent + + :ivar type: The type of the message. Required. Known values are: "text" and "image". + :vartype type: str or + ~azure.search.documents.knowledgebase.models.KnowledgeBaseMessageContentType + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the message. Required. Known values are: \"text\" and \"image\".""" + + @overload + def __init__( + self, + *, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseMessageImageContent(KnowledgeBaseMessageContent, discriminator="image"): + """Image message type. + + :ivar type: The discriminator value. Required. Image message content kind. + :vartype type: str or ~azure.search.documents.knowledgebase.models.IMAGE + :ivar image: The image content. Required. + :vartype image: ~azure.search.documents.knowledgebase.models.KnowledgeBaseImageContent + """ + + type: Literal[KnowledgeBaseMessageContentType.IMAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Image message content kind.""" + image: "_models.KnowledgeBaseImageContent" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The image content. Required.""" + + @overload + def __init__( + self, + *, + image: "_models.KnowledgeBaseImageContent", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseMessageContentType.IMAGE # type: ignore + + +class KnowledgeBaseMessageTextContent(KnowledgeBaseMessageContent, discriminator="text"): + """Text message type. + + :ivar type: The discriminator value. Required. Text message content kind. + :vartype type: str or ~azure.search.documents.knowledgebase.models.TEXT + :ivar text: The text content. Required. + :vartype text: str + """ + + type: Literal[KnowledgeBaseMessageContentType.TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Text message content kind.""" + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text content. Required.""" + + @overload + def __init__( + self, + *, + text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeBaseMessageContentType.TEXT # type: ignore + + +class KnowledgeBaseModelAnswerSynthesisActivityRecord( + KnowledgeBaseActivityRecord, discriminator="modelAnswerSynthesis" +): # pylint: disable=name-too-long + """Represents an LLM answer synthesis activity record. + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail + :ivar type: The discriminator value. Required. Default value is "modelAnswerSynthesis". + :vartype type: str + :ivar input_tokens: The number of input tokens for the LLM answer synthesis activity. + :vartype input_tokens: int + :ivar output_tokens: The number of output tokens for the LLM answer synthesis activity. + :vartype output_tokens: int + """ + + type: Literal["modelAnswerSynthesis"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"modelAnswerSynthesis\".""" + input_tokens: Optional[int] = rest_field( + name="inputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of input tokens for the LLM answer synthesis activity.""" + output_tokens: Optional[int] = rest_field( + name="outputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of output tokens for the LLM answer synthesis activity.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + input_tokens: Optional[int] = None, + output_tokens: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "modelAnswerSynthesis" # type: ignore + + +class KnowledgeBaseModelQueryPlanningActivityRecord( + KnowledgeBaseActivityRecord, discriminator="modelQueryPlanning" +): # pylint: disable=name-too-long + """Represents an LLM query planning activity record. + + :ivar id: The ID of the activity record. Required. + :vartype id: int + :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. + :vartype elapsed_ms: int + :ivar error: The error detail explaining why the operation failed. This property is only + included when the activity does not succeed. + :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail + :ivar type: The discriminator value. Required. Default value is "modelQueryPlanning". + :vartype type: str + :ivar input_tokens: The number of input tokens for the LLM query planning activity. + :vartype input_tokens: int + :ivar output_tokens: The number of output tokens for the LLM query planning activity. + :vartype output_tokens: int + """ + + type: Literal["modelQueryPlanning"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"modelQueryPlanning\".""" + input_tokens: Optional[int] = rest_field( + name="inputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of input tokens for the LLM query planning activity.""" + output_tokens: Optional[int] = rest_field( + name="outputTokens", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of output tokens for the LLM query planning activity.""" + + @overload + def __init__( + self, + *, + id: int, # pylint: disable=redefined-builtin + elapsed_ms: Optional[int] = None, + error: Optional["_models.KnowledgeBaseErrorDetail"] = None, + input_tokens: Optional[int] = None, + output_tokens: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "modelQueryPlanning" # type: ignore + + +class KnowledgeBaseRemoteSharePointReference(KnowledgeBaseReference, discriminator="remoteSharePoint"): + """Represents a remote SharePoint document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Default value is "remoteSharePoint". + :vartype type: str + :ivar web_url: The url the reference data originated from. Required. + :vartype web_url: str + :ivar search_sensitivity_label_info: Information about the sensitivity label applied to the + SharePoint document. + :vartype search_sensitivity_label_info: + ~azure.search.documents.knowledgebase.models.SharePointSensitivityLabelInfo + """ + + type: Literal["remoteSharePoint"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"remoteSharePoint\".""" + web_url: str = rest_field(name="webUrl", visibility=["read", "create", "update", "delete", "query"]) + """The url the reference data originated from. Required.""" + search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = rest_field( + name="searchSensitivityLabelInfo", visibility=["read", "create", "update", "delete", "query"] + ) + """Information about the sensitivity label applied to the SharePoint document.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + web_url: str, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "remoteSharePoint" # type: ignore + + +class KnowledgeBaseRetrievalRequest(_Model): + """The input contract for the retrieval request. + + :ivar messages: A list of chat message style input. + :vartype messages: list[~azure.search.documents.knowledgebase.models.KnowledgeBaseMessage] + :ivar intents: A list of intended queries to execute without model query planning. + :vartype intents: list[~azure.search.documents.knowledgebase.models.KnowledgeRetrievalIntent] + :ivar max_runtime_in_seconds: The maximum runtime in seconds. + :vartype max_runtime_in_seconds: int + :ivar max_output_size: Limits the maximum size of the content in the output. + :vartype max_output_size: int + :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. + :vartype retrieval_reasoning_effort: + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffort + :ivar include_activity: Indicates retrieval results should include activity information. + :vartype include_activity: bool + :ivar output_mode: The output configuration for this retrieval. Known values are: + "extractiveData" and "answerSynthesis". + :vartype output_mode: str or + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalOutputMode + :ivar knowledge_source_params: A list of runtime parameters for the knowledge sources. + :vartype knowledge_source_params: + list[~azure.search.documents.knowledgebase.models.KnowledgeSourceParams] + """ + + messages: Optional[list["_models.KnowledgeBaseMessage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of chat message style input.""" + intents: Optional[list["_models.KnowledgeRetrievalIntent"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of intended queries to execute without model query planning.""" + max_runtime_in_seconds: Optional[int] = rest_field( + name="maxRuntimeInSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum runtime in seconds.""" + max_output_size: Optional[int] = rest_field( + name="maxOutputSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Limits the maximum size of the content in the output.""" + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = rest_field( + name="retrievalReasoningEffort", visibility=["read", "create", "update", "delete", "query"] + ) + """The retrieval reasoning effort configuration.""" + include_activity: Optional[bool] = rest_field( + name="includeActivity", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates retrieval results should include activity information.""" + output_mode: Optional[Union[str, "_models.KnowledgeRetrievalOutputMode"]] = rest_field( + name="outputMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The output configuration for this retrieval. Known values are: \"extractiveData\" and + \"answerSynthesis\".""" + knowledge_source_params: Optional[list["_models.KnowledgeSourceParams"]] = rest_field( + name="knowledgeSourceParams", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of runtime parameters for the knowledge sources.""" + + @overload + def __init__( + self, + *, + messages: Optional[list["_models.KnowledgeBaseMessage"]] = None, + intents: Optional[list["_models.KnowledgeRetrievalIntent"]] = None, + max_runtime_in_seconds: Optional[int] = None, + max_output_size: Optional[int] = None, + retrieval_reasoning_effort: Optional["_models.KnowledgeRetrievalReasoningEffort"] = None, + include_activity: Optional[bool] = None, + output_mode: Optional[Union[str, "_models.KnowledgeRetrievalOutputMode"]] = None, + knowledge_source_params: Optional[list["_models.KnowledgeSourceParams"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseRetrievalResponse(_Model): + """The output contract for the retrieval response. + + :ivar response: The response messages. + :vartype response: list[~azure.search.documents.knowledgebase.models.KnowledgeBaseMessage] + :ivar activity: The activity records for tracking progress and billing implications. + :vartype activity: + list[~azure.search.documents.knowledgebase.models.KnowledgeBaseActivityRecord] + :ivar references: The references for the retrieval data used in the response. + :vartype references: list[~azure.search.documents.knowledgebase.models.KnowledgeBaseReference] + """ + + response: Optional[list["_models.KnowledgeBaseMessage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The response messages.""" + activity: Optional[list["_models.KnowledgeBaseActivityRecord"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The activity records for tracking progress and billing implications.""" + references: Optional[list["_models.KnowledgeBaseReference"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The references for the retrieval data used in the response.""" + + @overload + def __init__( + self, + *, + response: Optional[list["_models.KnowledgeBaseMessage"]] = None, + activity: Optional[list["_models.KnowledgeBaseActivityRecord"]] = None, + references: Optional[list["_models.KnowledgeBaseReference"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeBaseSearchIndexReference(KnowledgeBaseReference, discriminator="searchIndex"): + """Represents an Azure Search document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Default value is "searchIndex". + :vartype type: str + :ivar doc_key: The document key for the reference. + :vartype doc_key: str + """ + + type: Literal["searchIndex"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"searchIndex\".""" + doc_key: Optional[str] = rest_field(name="docKey", visibility=["read", "create", "update", "delete", "query"]) + """The document key for the reference.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + doc_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "searchIndex" # type: ignore + + +class KnowledgeBaseWebReference(KnowledgeBaseReference, discriminator="web"): + """Represents a web document reference. + + :ivar id: The ID of the reference. Required. + :vartype id: str + :ivar activity_source: The source activity ID for the reference. Required. + :vartype activity_source: int + :ivar source_data: The source data for the reference. + :vartype source_data: dict[str, str] + :ivar reranker_score: The reranker score for the document reference. + :vartype reranker_score: float + :ivar type: The discriminator value. Required. Default value is "web". + :vartype type: str + :ivar url: The url the reference data originated from. Required. + :vartype url: str + :ivar title: The title of the web document. + :vartype title: str + """ + + type: Literal["web"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Default value is \"web\".""" + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The url the reference data originated from. Required.""" + title: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The title of the web document.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + activity_source: int, + url: str, + source_data: Optional[dict[str, str]] = None, + reranker_score: Optional[float] = None, + title: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = "web" # type: ignore + + +class KnowledgeRetrievalReasoningEffort(_Model): + """Base type for reasoning effort. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeRetrievalHighReasoningEffort, KnowledgeRetrievalLowReasoningEffort, + KnowledgeRetrievalMediumReasoningEffort, KnowledgeRetrievalMinimalReasoningEffort + + :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", + "medium", and "high". + :vartype kind: str or + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffortKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The kind of reasoning effort. Required. Known values are: \"minimal\", \"low\", \"medium\", and + \"high\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeRetrievalHighReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="high"): + """Run knowledge retrieval with high reasoning effort. + + :ivar kind: The discriminator value. Required. Use a high amount of reasoning during retrieval. + :vartype kind: str or ~azure.search.documents.knowledgebase.models.HIGH + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.HIGH] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Use a high amount of reasoning during retrieval.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.HIGH # type: ignore + + +class KnowledgeRetrievalIntent(_Model): + """An intended query to execute without model query planning. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeRetrievalSemanticIntent + + :ivar type: The type of the intent. Required. "semantic" + :vartype type: str or ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalIntentType + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the intent. Required. \"semantic\"""" + + @overload + def __init__( + self, + *, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KnowledgeRetrievalLowReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="low"): + """Run knowledge retrieval with low reasoning effort. + + :ivar kind: The discriminator value. Required. Use low reasoning during retrieval. + :vartype kind: str or ~azure.search.documents.knowledgebase.models.LOW + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.LOW] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Use low reasoning during retrieval.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.LOW # type: ignore + + +class KnowledgeRetrievalMediumReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="medium"): + """Run knowledge retrieval with medium reasoning effort. + + :ivar kind: The discriminator value. Required. Use a moderate amount of reasoning during + retrieval. + :vartype kind: str or ~azure.search.documents.knowledgebase.models.MEDIUM + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.MEDIUM] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Use a moderate amount of reasoning during retrieval.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.MEDIUM # type: ignore + + +class KnowledgeRetrievalMinimalReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="minimal"): + """Run knowledge retrieval with minimal reasoning effort. + + :ivar kind: The discriminator value. Required. Does not perform any source selections, any + query planning, or any iterative search. + :vartype kind: str or ~azure.search.documents.knowledgebase.models.MINIMAL + """ + + kind: Literal[KnowledgeRetrievalReasoningEffortKind.MINIMAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Does not perform any source selections, any query planning, + or any iterative search.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeRetrievalReasoningEffortKind.MINIMAL # type: ignore + + +class KnowledgeRetrievalSemanticIntent(KnowledgeRetrievalIntent, discriminator="semantic"): + """A semantic query intent. + + :ivar type: The discriminator value. Required. A natural language semantic query intent. + :vartype type: str or ~azure.search.documents.knowledgebase.models.SEMANTIC + :ivar search: The semantic query to execute. Required. + :vartype search: str + """ + + type: Literal[KnowledgeRetrievalIntentType.SEMANTIC] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A natural language semantic query intent.""" + search: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The semantic query to execute. Required.""" + + @overload + def __init__( + self, + *, + search: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = KnowledgeRetrievalIntentType.SEMANTIC # type: ignore + + +class RemoteSharePointKnowledgeSourceParams(KnowledgeSourceParams, discriminator="remoteSharePoint"): + """Specifies runtime parameters for a remote SharePoint knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from remote + SharePoint. + :vartype kind: str or ~azure.search.documents.indexes.models.REMOTE_SHARE_POINT + :ivar filter_expression_add_on: A filter condition applied to the SharePoint data source. It + must be specified in the Keyword Query Language syntax. It will be combined as a conjunction + with the filter expression specified in the knowledge source definition. + :vartype filter_expression_add_on: str + """ + + kind: Literal[KnowledgeSourceKind.REMOTE_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from remote SharePoint.""" + filter_expression_add_on: Optional[str] = rest_field( + name="filterExpressionAddOn", visibility=["read", "create", "update", "delete", "query"] + ) + """A filter condition applied to the SharePoint data source. It must be specified in the Keyword + Query Language syntax. It will be combined as a conjunction with the filter expression + specified in the knowledge source definition.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + filter_expression_add_on: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.REMOTE_SHARE_POINT # type: ignore + + +class SearchIndexKnowledgeSourceParams(KnowledgeSourceParams, discriminator="searchIndex"): + """Specifies runtime parameters for a search index knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from a Search + Index. + :vartype kind: str or ~azure.search.documents.indexes.models.SEARCH_INDEX + :ivar filter_add_on: A filter condition applied to the index (e.g., 'State eq VA'). + :vartype filter_add_on: str + """ + + kind: Literal[KnowledgeSourceKind.SEARCH_INDEX] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from a Search Index.""" + filter_add_on: Optional[str] = rest_field( + name="filterAddOn", visibility=["read", "create", "update", "delete", "query"] + ) + """A filter condition applied to the index (e.g., 'State eq VA').""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + filter_add_on: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.SEARCH_INDEX # type: ignore + + +class SharePointSensitivityLabelInfo(_Model): + """Information about the sensitivity label applied to a SharePoint document. + + :ivar display_name: The display name for the sensitivity label. + :vartype display_name: str + :ivar sensitivity_label_id: The ID of the sensitivity label. + :vartype sensitivity_label_id: str + :ivar tooltip: The tooltip that should be displayed for the label in a UI. + :vartype tooltip: str + :ivar priority: The priority in which the sensitivity label is applied. + :vartype priority: int + :ivar color: The color that the UI should display for the label, if configured. + :vartype color: str + :ivar is_encrypted: Indicates whether the sensitivity label enforces encryption. + :vartype is_encrypted: bool + """ + + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """The display name for the sensitivity label.""" + sensitivity_label_id: Optional[str] = rest_field( + name="sensitivityLabelId", visibility=["read", "create", "update", "delete", "query"] + ) + """The ID of the sensitivity label.""" + tooltip: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The tooltip that should be displayed for the label in a UI.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The priority in which the sensitivity label is applied.""" + color: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The color that the UI should display for the label, if configured.""" + is_encrypted: Optional[bool] = rest_field( + name="isEncrypted", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether the sensitivity label enforces encryption.""" + + @overload + def __init__( + self, + *, + display_name: Optional[str] = None, + sensitivity_label_id: Optional[str] = None, + tooltip: Optional[str] = None, + priority: Optional[int] = None, + color: Optional[str] = None, + is_encrypted: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class WebKnowledgeSourceParams(KnowledgeSourceParams, discriminator="web"): + """Specifies runtime parameters for a web knowledge source. + + :ivar knowledge_source_name: The name of the index the params apply to. Required. + :vartype knowledge_source_name: str + :ivar include_references: Indicates whether references should be included for data retrieved + from this source. + :vartype include_references: bool + :ivar include_reference_source_data: Indicates whether references should include the structured + data obtained during retrieval in their payload. + :vartype include_reference_source_data: bool + :ivar always_query_source: Indicates that this knowledge source should bypass source selection + and always be queried at retrieval time. + :vartype always_query_source: bool + :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be + included in the response. + :vartype reranker_threshold: float + :ivar kind: The discriminator value. Required. A knowledge source that reads data from the web. + :vartype kind: str or ~azure.search.documents.indexes.models.WEB + :ivar language: The language of the web results. + :vartype language: str + :ivar market: The market of the web results. + :vartype market: str + :ivar count: The number of web results to return. + :vartype count: int + :ivar freshness: The freshness of web results. + :vartype freshness: str + """ + + kind: Literal[KnowledgeSourceKind.WEB] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. A knowledge source that reads data from the web.""" + language: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The language of the web results.""" + market: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The market of the web results.""" + count: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of web results to return.""" + freshness: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The freshness of web results.""" + + @overload + def __init__( + self, + *, + knowledge_source_name: str, + include_references: Optional[bool] = None, + include_reference_source_data: Optional[bool] = None, + always_query_source: Optional[bool] = None, + reranker_threshold: Optional[float] = None, + language: Optional[str] = None, + market: Optional[str] = None, + count: Optional[int] = None, + freshness: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = KnowledgeSourceKind.WEB # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/__init__.py similarity index 70% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/__init__.py index ee2a3f9ac8bb..48bd23b4f6a7 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._knowledge_retrieval_operations import KnowledgeRetrievalOperations # type: ignore +from ._operations import KnowledgeRetrievalOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py new file mode 100644 index 000000000000..f353833f4cb9 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py @@ -0,0 +1,283 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1 +from ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.serialization import Deserializer, Serializer +from ..._validation import api_version_validation +from .._configuration import KnowledgeBaseRetrievalClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_knowledge_retrieval_retrieve_request( # pylint: disable=name-too-long + knowledge_base_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/retrieve/{knowledgeBaseName}" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class KnowledgeRetrievalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.KnowledgeBaseRetrievalClient`'s + :attr:`knowledge_retrieval` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: KnowledgeBaseRetrievalClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def retrieve( + self, + knowledge_base_name: str, + retrieval_request: _models1.KnowledgeBaseRetrievalRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: + ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def retrieve( + self, + knowledge_base_name: str, + retrieval_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def retrieve( + self, + knowledge_base_name: str, + retrieval_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Required. + :type retrieval_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2025-11-01-preview", + params_added_on={ + "2025-11-01-preview": [ + "api_version", + "knowledge_base_name", + "query_source_authorization", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2025-11-01-preview"], + ) + def retrieve( + self, + knowledge_base_name: str, + retrieval_request: Union[_models1.KnowledgeBaseRetrievalRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.KnowledgeBaseRetrievalResponse: + """KnowledgeBase retrieves relevant data from backing stores. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param retrieval_request: The retrieval request to process. Is one of the following types: + KnowledgeBaseRetrievalRequest, JSON, IO[bytes] Required. + :type retrieval_request: + ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: KnowledgeBaseRetrievalResponse. The KnowledgeBaseRetrievalResponse is compatible with + MutableMapping + :rtype: ~azure.search.documents.knowledgebase.models.KnowledgeBaseRetrievalResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.KnowledgeBaseRetrievalResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(retrieval_request, (IOBase, bytes)): + _content = retrieval_request + else: + _content = json.dumps(retrieval_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_retrieval_retrieve_request( + knowledge_base_name=knowledge_base_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeBaseRetrievalResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 3ca7c8d417d7..86d9675d77ac 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -1,40 +1,67 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from .._generated.models import ( - AutocompleteMode, +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AutocompleteItem, + AutocompleteRequest, + AutocompleteResult, DebugInfo, - HybridCountAndFacetMode, + DocumentDebugInfo, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + FacetResult, HybridSearch, IndexAction, + IndexBatch, + IndexDocumentsResult, IndexingResult, + LookupDocument, QueryAnswerResult, - QueryAnswerType, QueryCaptionResult, QueryResultDocumentInnerHit, + QueryResultDocumentRerankerInput, + QueryResultDocumentSemanticField, + QueryResultDocumentSubscores, + QueryRewritesDebugInfo, + QueryRewritesValuesDebugInfo, + SearchDocumentsResult, + SearchRequest, + SearchResult, + SearchScoreThreshold, + SemanticDebugInfo, + SingleVectorFieldResult, + SuggestDocumentsResult, + SuggestRequest, + SuggestResult, + TextResult, + VectorQuery, + VectorSimilarityThreshold, + VectorThreshold, + VectorizableImageBinaryQuery, + VectorizableImageUrlQuery, + VectorizableTextQuery, + VectorizedQuery, + VectorsDebugInfo, +) + +from ._enums import ( # type: ignore + AutocompleteMode, + HybridCountAndFacetMode, + IndexActionType, + QueryAnswerType, QueryCaptionType, QueryDebugMode, QueryLanguage, @@ -43,33 +70,65 @@ QueryType, ScoringStatistics, SearchMode, - SearchScoreThreshold, SemanticErrorMode, SemanticErrorReason, + SemanticFieldState, + SemanticQueryRewritesResultType, SemanticSearchResultsType, VectorFilterMode, - VectorSimilarityThreshold, - VectorThreshold, + VectorQueryKind, VectorThresholdKind, - VectorizableImageBinaryQuery, - VectorizableImageUrlQuery, - VectorizedQuery, - VectorizableTextQuery, - VectorQuery, ) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk - -__all__ = ( - "AutocompleteMode", +__all__ = [ + "AutocompleteItem", + "AutocompleteRequest", + "AutocompleteResult", "DebugInfo", - "HybridCountAndFacetMode", + "DocumentDebugInfo", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "FacetResult", "HybridSearch", "IndexAction", + "IndexBatch", + "IndexDocumentsResult", "IndexingResult", + "LookupDocument", "QueryAnswerResult", - "QueryAnswerType", "QueryCaptionResult", "QueryResultDocumentInnerHit", + "QueryResultDocumentRerankerInput", + "QueryResultDocumentSemanticField", + "QueryResultDocumentSubscores", + "QueryRewritesDebugInfo", + "QueryRewritesValuesDebugInfo", + "SearchDocumentsResult", + "SearchRequest", + "SearchResult", + "SearchScoreThreshold", + "SemanticDebugInfo", + "SingleVectorFieldResult", + "SuggestDocumentsResult", + "SuggestRequest", + "SuggestResult", + "TextResult", + "VectorQuery", + "VectorSimilarityThreshold", + "VectorThreshold", + "VectorizableImageBinaryQuery", + "VectorizableImageUrlQuery", + "VectorizableTextQuery", + "VectorizedQuery", + "VectorsDebugInfo", + "AutocompleteMode", + "HybridCountAndFacetMode", + "IndexActionType", + "QueryAnswerType", "QueryCaptionType", "QueryDebugMode", "QueryLanguage", @@ -78,17 +137,14 @@ "QueryType", "ScoringStatistics", "SearchMode", - "SearchScoreThreshold", "SemanticErrorMode", "SemanticErrorReason", + "SemanticFieldState", + "SemanticQueryRewritesResultType", "SemanticSearchResultsType", "VectorFilterMode", - "VectorSimilarityThreshold", - "VectorThreshold", + "VectorQueryKind", "VectorThresholdKind", - "VectorizableImageBinaryQuery", - "VectorizableImageUrlQuery", - "VectorizedQuery", - "VectorizableTextQuery", - "VectorQuery", -) +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_search_index_client_enums.py b/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py similarity index 96% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/models/_search_index_client_enums.py rename to sdk/search/azure-search-documents/azure/search/documents/models/_enums.py index 8297cadb55f0..0d5ed03370b5 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_search_index_client_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -69,7 +71,7 @@ class QueryAnswerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): appending the pipe character ``|`` followed by the ``threshold-`` option after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is 0.7. The maximum character length of answers can be configured by appending the pipe character - '|' followed by the 'count-\\ :code:``', such as + '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. """ @@ -83,11 +85,11 @@ class QueryAnswerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class QueryCaptionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This parameter is only valid if the query type is ``semantic``. If set, the query returns captions extracted from key passages in the highest ranked documents. When Captions is set to - ``extractive``\\ , highlighting is enabled by default, and can be configured by appending the - pipe character ``|`` followed by the ``highlight-`` option, such as + ``extractive``, highlighting is enabled by default, and can be configured by appending the pipe + character ``|`` followed by the ``highlight-`` option, such as ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of captions - can be configured by appending the pipe character '|' followed by the 'count-\\ :code:``', such as 'extractive|maxcharlength-600'. + can be configured by appending the pipe character '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. """ NONE = "none" @@ -269,7 +271,7 @@ class QueryLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): class QueryRewritesType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This parameter is only valid if the query type is ``semantic``. When QueryRewrites is set to - ``generative``\\ , the query terms are sent to a generate model which will produce 10 (default) + ``generative``, the query terms are sent to a generate model which will produce 10 (default) rewrites to help increase the recall of the request. The requested count can be configured by appending the pipe character ``|`` followed by the ``count-`` option, such as ``generative|count-3``. Defaults to ``None``. @@ -397,8 +399,7 @@ class VectorFilterMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): PRE_FILTER = "preFilter" """The filter will be applied before the search query.""" STRICT_POST_FILTER = "strictPostFilter" - """The filter will be applied after the global top-k candidate set of vector results is returned. - This will result in fewer results than requested by the parameter 'k'.""" + """The filter will be applied after the global top-k candidate set of vector results is returned.""" class VectorQueryKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py new file mode 100644 index 000000000000..fda9f9667a56 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -0,0 +1,2184 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import VectorQueryKind, VectorThresholdKind + +if TYPE_CHECKING: + from .. import models as _models + + +class AutocompleteItem(_Model): + """The result of Autocomplete requests. + + :ivar text: The completed term. Required. + :vartype text: str + :ivar query_plus_text: The query along with the completed term. Required. + :vartype query_plus_text: str + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The completed term. Required.""" + query_plus_text: str = rest_field(name="queryPlusText", visibility=["read", "create", "update", "delete", "query"]) + """The query along with the completed term. Required.""" + + @overload + def __init__( + self, + *, + text: str, + query_plus_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AutocompleteRequest(_Model): + """Parameters for fuzzy matching, and other autocomplete query behaviors. + + :ivar search_text: The search text on which to base autocomplete results. Required. + :vartype search_text: str + :ivar autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + :vartype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :ivar filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. + :vartype filter: str + :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the autocomplete + query. Default is false. When set to true, the query will autocomplete terms even if there's a + substituted or missing character in the search text. While this provides a better experience in + some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and + consume more resources. + :vartype use_fuzzy_matching: bool + :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. + :vartype highlight_post_tag: str + :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. + :vartype highlight_pre_tag: str + :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by an autocomplete query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. + :vartype minimum_coverage: float + :ivar search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. + :vartype search_fields: str + :ivar suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :vartype suggester_name: str + :ivar top: The number of auto-completed terms to retrieve. This must be a value between 1 and + 100. The default is 5. + :vartype top: int + """ + + search_text: str = rest_field(name="search", visibility=["read", "create", "update", "delete", "query"]) + """The search text on which to base autocomplete results. Required.""" + autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = rest_field( + name="autocompleteMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the mode for Autocomplete. The default is 'oneTerm'. Use 'twoTerms' to get shingles + and 'oneTermWithContext' to use the current context while producing auto-completed terms. Known + values are: \"oneTerm\", \"twoTerms\", and \"oneTermWithContext\".""" + filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An OData expression that filters the documents used to produce completed terms for the + Autocomplete result.""" + use_fuzzy_matching: Optional[bool] = rest_field( + name="fuzzy", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to use fuzzy matching for the autocomplete query. Default is false. + When set to true, the query will autocomplete terms even if there's a substituted or missing + character in the search text. While this provides a better experience in some scenarios, it + comes at a performance cost as fuzzy autocomplete queries are slower and consume more + resources.""" + highlight_post_tag: Optional[str] = rest_field( + name="highlightPostTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, + hit highlighting is disabled.""" + highlight_pre_tag: Optional[str] = rest_field( + name="highlightPreTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If + omitted, hit highlighting is disabled.""" + minimum_coverage: Optional[float] = rest_field( + name="minimumCoverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A number between 0 and 100 indicating the percentage of the index that must be covered by an + autocomplete query in order for the query to be reported as a success. This parameter can be + useful for ensuring search availability even for services with only one replica. The default is + 80.""" + search_fields: Optional[str] = rest_field( + name="searchFields", visibility=["read", "create", "update", "delete", "query"] + ) + """The comma-separated list of field names to consider when querying for auto-completed terms. + Target fields must be included in the specified suggester.""" + suggester_name: str = rest_field(name="suggesterName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the suggester as specified in the suggesters collection that's part of the index + definition. Required.""" + top: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of auto-completed terms to retrieve. This must be a value between 1 and 100. The + default is 5.""" + + @overload + def __init__( + self, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = None, + filter: Optional[str] = None, # pylint: disable=redefined-builtin + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AutocompleteResult(_Model): + """The result of Autocomplete query. + + :ivar coverage: A value indicating the percentage of the index that was considered by the + autocomplete request, or null if minimumCoverage was not specified in the request. + :vartype coverage: float + :ivar results: The list of returned Autocompleted items. Required. + :vartype results: list[~azure.search.documents.models.AutocompleteItem] + """ + + coverage: Optional[float] = rest_field( + name="@search.coverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating the percentage of the index that was considered by the autocomplete request, + or null if minimumCoverage was not specified in the request.""" + results: list["_models.AutocompleteItem"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of returned Autocompleted items. Required.""" + + @overload + def __init__( + self, + *, + results: list["_models.AutocompleteItem"], + coverage: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DebugInfo(_Model): + """Contains debugging information that can be used to further explore your search results. + + :ivar query_rewrites: Contains debugging information specific to query rewrites. + :vartype query_rewrites: ~azure.search.documents.models.QueryRewritesDebugInfo + """ + + query_rewrites: Optional["_models.QueryRewritesDebugInfo"] = rest_field(name="queryRewrites", visibility=["read"]) + """Contains debugging information specific to query rewrites.""" + + +class DocumentDebugInfo(_Model): + """Contains debugging information that can be used to further explore your search results. + + :ivar semantic: Contains debugging information specific to semantic ranking requests. + :vartype semantic: ~azure.search.documents.models.SemanticDebugInfo + :ivar vectors: Contains debugging information specific to vector and hybrid search. + :vartype vectors: ~azure.search.documents.models.VectorsDebugInfo + :ivar inner_hits: Contains debugging information specific to vectors matched within a + collection of complex types. + :vartype inner_hits: dict[str, + list[~azure.search.documents.models.QueryResultDocumentInnerHit]] + """ + + semantic: Optional["_models.SemanticDebugInfo"] = rest_field(visibility=["read"]) + """Contains debugging information specific to semantic ranking requests.""" + vectors: Optional["_models.VectorsDebugInfo"] = rest_field(visibility=["read"]) + """Contains debugging information specific to vector and hybrid search.""" + inner_hits: Optional[dict[str, list["_models.QueryResultDocumentInnerHit"]]] = rest_field( + name="innerHits", visibility=["read"] + ) + """Contains debugging information specific to vectors matched within a collection of complex + types.""" + + +class ErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: dict[str, str] + """ + + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The additional info type.""" + info: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The additional info.""" + + @overload + def __init__( + self, + *, + type: Optional[str] = None, + info: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ErrorDetail(_Model): + """The error detail. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.search.documents.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.search.documents.models.ErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error target.""" + details: Optional[list["_models.ErrorDetail"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The error details.""" + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read", "create", "update", "delete", "query"] + ) + """The error additional info.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + message: Optional[str] = None, + target: Optional[str] = None, + details: Optional[list["_models.ErrorDetail"]] = None, + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ErrorResponse(_Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.search.documents.models.ErrorDetail + """ + + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error object.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FacetResult(_Model): + """A single bucket of a facet query result. Reports the number of documents with a field value + falling within a particular range or having a particular value or interval. + + :ivar count: The approximate count of documents falling within the bucket described by this + facet. + :vartype count: int + :ivar facets: The nested facet query results for the search operation, organized as a + collection of buckets for each faceted field; null if the query did not contain any nested + facets. + :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] + :ivar sum: The resulting total sum for the facet when a sum metric is requested. + :vartype sum: int + """ + + count: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The approximate count of documents falling within the bucket described by this facet.""" + facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field(name="@search.facets", visibility=["read"]) + """The nested facet query results for the search operation, organized as a collection of buckets + for each faceted field; null if the query did not contain any nested facets.""" + sum: Optional[int] = rest_field(visibility=["read"]) + """The resulting total sum for the facet when a sum metric is requested.""" + + @overload + def __init__( + self, + *, + count: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class HybridSearch(_Model): + """TThe query parameters to configure hybrid search behaviors. + + :ivar max_text_recall_size: Determines the maximum number of documents to be retrieved by the + text query portion of a hybrid search request. Those documents will be combined with the + documents matching the vector queries to produce a single final list of results. Choosing a + larger maxTextRecallSize value will allow retrieving and paging through more documents (using + the top and skip parameters), at the cost of higher resource utilization and higher latency. + The value needs to be between 1 and 10,000. Default is 1000. + :vartype max_text_recall_size: int + :ivar count_and_facet_mode: Determines whether the count and facets should includes all + documents that matched the search query, or only the documents that are retrieved within the + 'maxTextRecallSize' window. Known values are: "countRetrievableResults" and "countAllResults". + :vartype count_and_facet_mode: str or ~azure.search.documents.models.HybridCountAndFacetMode + """ + + max_text_recall_size: Optional[int] = rest_field( + name="maxTextRecallSize", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines the maximum number of documents to be retrieved by the text query portion of a + hybrid search request. Those documents will be combined with the documents matching the vector + queries to produce a single final list of results. Choosing a larger maxTextRecallSize value + will allow retrieving and paging through more documents (using the top and skip parameters), at + the cost of higher resource utilization and higher latency. The value needs to be between 1 and + 10,000. Default is 1000.""" + count_and_facet_mode: Optional[Union[str, "_models.HybridCountAndFacetMode"]] = rest_field( + name="countAndFacetMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether the count and facets should includes all documents that matched the search + query, or only the documents that are retrieved within the 'maxTextRecallSize' window. Known + values are: \"countRetrievableResults\" and \"countAllResults\".""" + + @overload + def __init__( + self, + *, + max_text_recall_size: Optional[int] = None, + count_and_facet_mode: Optional[Union[str, "_models.HybridCountAndFacetMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexAction(_Model): + """Represents an index action that operates on a document. + + :ivar action_type: The operation to perform on a document in an indexing batch. Known values + are: "upload", "merge", "mergeOrUpload", and "delete". + :vartype action_type: str or ~azure.search.documents.models.IndexActionType + """ + + action_type: Optional[Union[str, "_models.IndexActionType"]] = rest_field( + name="@search.action", visibility=["read", "create", "update", "delete", "query"] + ) + """The operation to perform on a document in an indexing batch. Known values are: \"upload\", + \"merge\", \"mergeOrUpload\", and \"delete\".""" + + @overload + def __init__( + self, + *, + action_type: Optional[Union[str, "_models.IndexActionType"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexBatch(_Model): + """Contains a batch of document write actions to send to the index. + + :ivar actions: The actions in the batch. Required. + :vartype actions: list[~azure.search.documents.models.IndexAction] + """ + + actions: list["_models.IndexAction"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The actions in the batch. Required.""" + + @overload + def __init__( + self, + *, + actions: list["_models.IndexAction"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexDocumentsResult(_Model): + """Response containing the status of operations for all documents in the indexing request. + + :ivar results: The list of status information for each document in the indexing request. + Required. + :vartype results: list[~azure.search.documents.models.IndexingResult] + """ + + results: list["_models.IndexingResult"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of status information for each document in the indexing request. Required.""" + + @overload + def __init__( + self, + *, + results: list["_models.IndexingResult"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IndexingResult(_Model): + """Status of an indexing operation for a single document. + + :ivar key: The key of a document that was in the indexing request. Required. + :vartype key: str + :ivar error_message: The error message explaining why the indexing operation failed for the + document identified by the key; null if indexing succeeded. + :vartype error_message: str + :ivar succeeded: A value indicating whether the indexing operation succeeded for the document + identified by the key. Required. + :vartype succeeded: bool + :ivar status_code: The status code of the indexing operation. Possible values include: 200 for + a successful update or delete, 201 for successful document creation, 400 for a malformed input + document, 404 for document not found, 409 for a version conflict, 422 when the index is + temporarily unavailable, or 503 for when the service is too busy. Required. + :vartype status_code: int + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key of a document that was in the indexing request. Required.""" + error_message: Optional[str] = rest_field( + name="errorMessage", visibility=["read", "create", "update", "delete", "query"] + ) + """The error message explaining why the indexing operation failed for the document identified by + the key; null if indexing succeeded.""" + succeeded: bool = rest_field(name="status", visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether the indexing operation succeeded for the document identified by the + key. Required.""" + status_code: int = rest_field(name="statusCode", visibility=["read", "create", "update", "delete", "query"]) + """The status code of the indexing operation. Possible values include: 200 for a successful update + or delete, 201 for successful document creation, 400 for a malformed input document, 404 for + document not found, 409 for a version conflict, 422 when the index is temporarily unavailable, + or 503 for when the service is too busy. Required.""" + + @overload + def __init__( + self, + *, + key: str, + succeeded: bool, + status_code: int, + error_message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LookupDocument(_Model): + """A document retrieved via a document lookup operation.""" + + +class QueryAnswerResult(_Model): + """An answer is a text passage extracted from the contents of the most relevant documents that + matched the query. Answers are extracted from the top search results. Answer candidates are + scored and the top answers are selected. + + :ivar score: The score value represents how relevant the answer is to the query relative to + other answers returned for the query. + :vartype score: float + :ivar key: The key of the document the answer was extracted from. + :vartype key: str + :ivar text: The text passage extracted from the document contents as the answer. + :vartype text: str + :ivar highlights: Same text passage as in the Text property with highlighted text phrases most + relevant to the query. + :vartype highlights: str + """ + + score: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The score value represents how relevant the answer is to the query relative to other answers + returned for the query.""" + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The key of the document the answer was extracted from.""" + text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text passage extracted from the document contents as the answer.""" + highlights: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Same text passage as in the Text property with highlighted text phrases most relevant to the + query.""" + + @overload + def __init__( + self, + *, + score: Optional[float] = None, + key: Optional[str] = None, + text: Optional[str] = None, + highlights: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueryCaptionResult(_Model): + """Captions are the most representative passages from the document relatively to the search query. + They are often used as document summary. Captions are only returned for queries of type + ``semantic``. + + :ivar text: A representative text passage extracted from the document most relevant to the + search query. + :vartype text: str + :ivar highlights: Same text passage as in the Text property with highlighted phrases most + relevant to the query. + :vartype highlights: str + """ + + text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A representative text passage extracted from the document most relevant to the search query.""" + highlights: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Same text passage as in the Text property with highlighted phrases most relevant to the query.""" + + @overload + def __init__( + self, + *, + text: Optional[str] = None, + highlights: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueryResultDocumentInnerHit(_Model): + """Detailed scoring information for an individual element of a complex collection. + + :ivar ordinal: Position of this specific matching element within it's original collection. + Position starts at 0. + :vartype ordinal: int + :ivar vectors: Detailed scoring information for an individual element of a complex collection + that matched a vector query. + :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] + """ + + ordinal: Optional[int] = rest_field(visibility=["read"]) + """Position of this specific matching element within it's original collection. Position starts at + 0.""" + vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = rest_field(visibility=["read"]) + """Detailed scoring information for an individual element of a complex collection that matched a + vector query.""" + + +class QueryResultDocumentRerankerInput(_Model): + """The raw concatenated strings that were sent to the semantic enrichment process. + + :ivar title: The raw string for the title field that was used for semantic enrichment. + :vartype title: str + :ivar content: The raw concatenated strings for the content fields that were used for semantic + enrichment. + :vartype content: str + :ivar keywords: The raw concatenated strings for the keyword fields that were used for semantic + enrichment. + :vartype keywords: str + """ + + title: Optional[str] = rest_field(visibility=["read"]) + """The raw string for the title field that was used for semantic enrichment.""" + content: Optional[str] = rest_field(visibility=["read"]) + """The raw concatenated strings for the content fields that were used for semantic enrichment.""" + keywords: Optional[str] = rest_field(visibility=["read"]) + """The raw concatenated strings for the keyword fields that were used for semantic enrichment.""" + + +class QueryResultDocumentSemanticField(_Model): + """Description of fields that were sent to the semantic enrichment process, as well as how they + were used. + + :ivar name: The name of the field that was sent to the semantic enrichment process. + :vartype name: str + :ivar state: The way the field was used for the semantic enrichment process (fully used, + partially used, or unused). Known values are: "used", "unused", and "partial". + :vartype state: str or ~azure.search.documents.models.SemanticFieldState + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the field that was sent to the semantic enrichment process.""" + state: Optional[Union[str, "_models.SemanticFieldState"]] = rest_field(visibility=["read"]) + """The way the field was used for the semantic enrichment process (fully used, partially used, or + unused). Known values are: \"used\", \"unused\", and \"partial\".""" + + +class QueryResultDocumentSubscores(_Model): + """The breakdown of subscores between the text and vector query components of the search query for + this document. Each vector query is shown as a separate object in the same order they were + received. + + :ivar text: The BM25 or Classic score for the text portion of the query. + :vartype text: ~azure.search.documents.models.TextResult + :ivar vectors: The vector similarity and @search.score values for each vector query. + :vartype vectors: list[dict[str, ~azure.search.documents.models.SingleVectorFieldResult]] + :ivar document_boost: The BM25 or Classic score for the text portion of the query. + :vartype document_boost: float + """ + + text: Optional["_models.TextResult"] = rest_field(visibility=["read"]) + """The BM25 or Classic score for the text portion of the query.""" + vectors: Optional[list[dict[str, "_models.SingleVectorFieldResult"]]] = rest_field(visibility=["read"]) + """The vector similarity and @search.score values for each vector query.""" + document_boost: Optional[float] = rest_field(name="documentBoost", visibility=["read"]) + """The BM25 or Classic score for the text portion of the query.""" + + +class QueryRewritesDebugInfo(_Model): + """Contains debugging information specific to query rewrites. + + :ivar text: List of query rewrites generated for the text query. + :vartype text: ~azure.search.documents.models.QueryRewritesValuesDebugInfo + :ivar vectors: List of query rewrites generated for the vectorizable text queries. + :vartype vectors: list[~azure.search.documents.models.QueryRewritesValuesDebugInfo] + """ + + text: Optional["_models.QueryRewritesValuesDebugInfo"] = rest_field(visibility=["read"]) + """List of query rewrites generated for the text query.""" + vectors: Optional[list["_models.QueryRewritesValuesDebugInfo"]] = rest_field(visibility=["read"]) + """List of query rewrites generated for the vectorizable text queries.""" + + +class QueryRewritesValuesDebugInfo(_Model): + """Contains debugging information specific to query rewrites. + + :ivar input_query: The input text to the generative query rewriting model. There may be cases + where the user query and the input to the generative model are not identical. + :vartype input_query: str + :ivar rewrites: List of query rewrites. + :vartype rewrites: list[str] + """ + + input_query: Optional[str] = rest_field(name="inputQuery", visibility=["read"]) + """The input text to the generative query rewriting model. There may be cases where the user query + and the input to the generative model are not identical.""" + rewrites: Optional[list[str]] = rest_field(visibility=["read"]) + """List of query rewrites.""" + + +class SearchDocumentsResult(_Model): + """Response containing search results from an index. + + :ivar count: The total count of results found by the search operation, or null if the count was + not requested. If present, the count may be greater than the number of results in this + response. This can happen if you use the $top or $skip parameters, or if the query can't return + all the requested documents in a single response. + :vartype count: int + :ivar coverage: A value indicating the percentage of the index that was included in the query, + or null if minimumCoverage was not specified in the request. + :vartype coverage: float + :ivar facets: The facet query results for the search operation, organized as a collection of + buckets for each faceted field; null if the query did not include any facet expressions. + :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] + :ivar answers: The answers query results for the search operation; null if the answers query + parameter was not specified or set to 'none'. + :vartype answers: list[~azure.search.documents.models.QueryAnswerResult] + :ivar debug_info: Debug information that applies to the search results as a whole. + :vartype debug_info: ~azure.search.documents.models.DebugInfo + :ivar next_page_parameters: Continuation JSON payload returned when the query can't return all + the requested results in a single response. You can use this JSON along with @odata.nextLink to + formulate another POST Search request to get the next part of the search response. + :vartype next_page_parameters: ~azure.search.documents.models.SearchRequest + :ivar results: The sequence of results returned by the query. Required. + :vartype results: list[~azure.search.documents.models.SearchResult] + :ivar next_link: Continuation URL returned when the query can't return all the requested + results in a single response. You can use this URL to formulate another GET or POST Search + request to get the next part of the search response. Make sure to use the same verb (GET or + POST) as the request that produced this response. + :vartype next_link: str + :ivar semantic_partial_response_reason: Reason that a partial response was returned for a + semantic ranking request. Known values are: "maxWaitExceeded", "capacityOverloaded", and + "transient". + :vartype semantic_partial_response_reason: str or + ~azure.search.documents.models.SemanticErrorReason + :ivar semantic_partial_response_type: Type of partial response that was returned for a semantic + ranking request. Known values are: "baseResults" and "rerankedResults". + :vartype semantic_partial_response_type: str or + ~azure.search.documents.models.SemanticSearchResultsType + :ivar semantic_query_rewrites_result_type: Type of query rewrite that was used to retrieve + documents. "originalQueryOnly" + :vartype semantic_query_rewrites_result_type: str or + ~azure.search.documents.models.SemanticQueryRewritesResultType + """ + + count: Optional[int] = rest_field(name="@odata.count", visibility=["read", "create", "update", "delete", "query"]) + """The total count of results found by the search operation, or null if the count was not + requested. If present, the count may be greater than the number of results in this response. + This can happen if you use the $top or $skip parameters, or if the query can't return all the + requested documents in a single response.""" + coverage: Optional[float] = rest_field( + name="@search.coverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating the percentage of the index that was included in the query, or null if + minimumCoverage was not specified in the request.""" + facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field( + name="@search.facets", visibility=["read", "create", "update", "delete", "query"] + ) + """The facet query results for the search operation, organized as a collection of buckets for each + faceted field; null if the query did not include any facet expressions.""" + answers: Optional[list["_models.QueryAnswerResult"]] = rest_field( + name="@search.answers", visibility=["read", "create", "update", "delete", "query"] + ) + """The answers query results for the search operation; null if the answers query parameter was not + specified or set to 'none'.""" + debug_info: Optional["_models.DebugInfo"] = rest_field(name="@search.debug", visibility=["read"]) + """Debug information that applies to the search results as a whole.""" + next_page_parameters: Optional["_models.SearchRequest"] = rest_field( + name="@search.nextPageParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Continuation JSON payload returned when the query can't return all the requested results in a + single response. You can use this JSON along with @odata.nextLink to formulate another POST + Search request to get the next part of the search response.""" + results: list["_models.SearchResult"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The sequence of results returned by the query. Required.""" + next_link: Optional[str] = rest_field( + name="@odata.nextLink", visibility=["read", "create", "update", "delete", "query"] + ) + """Continuation URL returned when the query can't return all the requested results in a single + response. You can use this URL to formulate another GET or POST Search request to get the next + part of the search response. Make sure to use the same verb (GET or POST) as the request that + produced this response.""" + semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = rest_field( + name="@search.semanticPartialResponseReason", visibility=["read", "create", "update", "delete", "query"] + ) + """Reason that a partial response was returned for a semantic ranking request. Known values are: + \"maxWaitExceeded\", \"capacityOverloaded\", and \"transient\".""" + semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = rest_field( + name="@search.semanticPartialResponseType", visibility=["read", "create", "update", "delete", "query"] + ) + """Type of partial response that was returned for a semantic ranking request. Known values are: + \"baseResults\" and \"rerankedResults\".""" + semantic_query_rewrites_result_type: Optional[Union[str, "_models.SemanticQueryRewritesResultType"]] = rest_field( + name="@search.semanticQueryRewritesResultType", visibility=["read"] + ) + """Type of query rewrite that was used to retrieve documents. \"originalQueryOnly\"""" + + @overload + def __init__( + self, + *, + results: list["_models.SearchResult"], + count: Optional[int] = None, + coverage: Optional[float] = None, + facets: Optional[dict[str, list["_models.FacetResult"]]] = None, + answers: Optional[list["_models.QueryAnswerResult"]] = None, + next_page_parameters: Optional["_models.SearchRequest"] = None, + next_link: Optional[str] = None, + semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = None, + semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchRequest(_Model): + """Parameters for filtering, sorting, faceting, paging, and other search query behaviors. + + :ivar include_total_result_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. + :vartype include_total_result_count: bool + :ivar facets: The list of facet expressions to apply to the search query. Each facet expression + contains a field name, optionally followed by a comma-separated list of name:value pairs. + :vartype facets: list[str] + :ivar filter: The OData $filter expression to apply to the search query. + :vartype filter: str + :ivar highlight_fields: The comma-separated list of field names to use for hit highlights. Only + searchable fields can be used for hit highlighting. + :vartype highlight_fields: str + :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. + :vartype highlight_post_tag: str + :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. + :vartype highlight_pre_tag: str + :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. + :vartype minimum_coverage: float + :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :vartype order_by: str + :ivar query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". + :vartype query_type: str or ~azure.search.documents.models.QueryType + :ivar scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". + :vartype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :ivar session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. + :vartype session_id: str + :ivar scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). + :vartype scoring_parameters: list[str] + :ivar scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. + :vartype scoring_profile: str + :ivar debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". + :vartype debug: str or ~azure.search.documents.models.QueryDebugMode + :ivar search_text: A full-text search query expression; Use "*" or omit this parameter to match + all documents. + :vartype search_text: str + :ivar search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. + :vartype search_fields: str + :ivar search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". + :vartype search_mode: str or ~azure.search.documents.models.SearchMode + :ivar query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". + :vartype query_language: str or ~azure.search.documents.models.QueryLanguage + :ivar speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". + :vartype speller: str or ~azure.search.documents.models.QuerySpellerType + :ivar select: The comma-separated list of fields to retrieve. If unspecified, all fields marked + as retrievable in the schema are included. + :vartype select: str + :ivar skip: The number of search results to skip. This value cannot be greater than 100,000. If + you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. + :vartype skip: int + :ivar top: The number of search results to retrieve. This can be used in conjunction with $skip + to implement client-side paging of search results. If results are truncated due to server-side + paging, the response will include a continuation token that can be used to issue another Search + request for the next page of results. + :vartype top: int + :ivar semantic_configuration: The name of a semantic configuration that will be used when + processing documents for queries of type semantic. + :vartype semantic_configuration: str + :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". + :vartype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :ivar semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of + time it takes for semantic enrichment to finish processing before the request fails. + :vartype semantic_max_wait_in_milliseconds: int + :ivar semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. + :vartype semantic_query: str + :ivar answers: A value that specifies whether answers should be returned as part of the search + response. Known values are: "none" and "extractive". + :vartype answers: str or ~azure.search.documents.models.QueryAnswerType + :ivar captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". + :vartype captions: str or ~azure.search.documents.models.QueryCaptionType + :ivar query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". + :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :ivar semantic_fields: The comma-separated list of field names used for semantic ranking. + :vartype semantic_fields: str + :ivar vector_queries: The query parameters for vector and hybrid search queries. + :vartype vector_queries: list[~azure.search.documents.models.VectorQuery] + :ivar vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". + :vartype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :ivar hybrid_search: The query parameters to configure hybrid search behaviors. + :vartype hybrid_search: ~azure.search.documents.models.HybridSearch + """ + + include_total_result_count: Optional[bool] = rest_field( + name="count", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether to fetch the total count of results. Default is false. Setting + this value to true may have a performance impact. Note that the count returned is an + approximation.""" + facets: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of facet expressions to apply to the search query. Each facet expression contains a + field name, optionally followed by a comma-separated list of name:value pairs.""" + filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The OData $filter expression to apply to the search query.""" + highlight_fields: Optional[str] = rest_field( + name="highlight", visibility=["read", "create", "update", "delete", "query"] + ) + """The comma-separated list of field names to use for hit highlights. Only searchable fields can + be used for hit highlighting.""" + highlight_post_tag: Optional[str] = rest_field( + name="highlightPostTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is + </em>.""" + highlight_pre_tag: Optional[str] = rest_field( + name="highlightPreTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is prepended to hit highlights. Must be set with highlightPostTag. Default is + <em>.""" + minimum_coverage: Optional[float] = rest_field( + name="minimumCoverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A number between 0 and 100 indicating the percentage of the index that must be covered by a + search query in order for the query to be reported as a success. This parameter can be useful + for ensuring search availability even for services with only one replica. The default is 100.""" + order_by: Optional[str] = rest_field(name="orderby", visibility=["read", "create", "update", "delete", "query"]) + """The comma-separated list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses.""" + query_type: Optional[Union[str, "_models.QueryType"]] = rest_field( + name="queryType", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if + your query uses the Lucene query syntax. Known values are: \"simple\", \"full\", and + \"semantic\".""" + scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = rest_field( + name="scoringStatistics", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether we want to calculate scoring statistics (such as document + frequency) globally for more consistent scoring, or locally, for lower latency. The default is + 'local'. Use 'global' to aggregate scoring statistics globally before scoring. Using global + scoring statistics can increase latency of search queries. Known values are: \"local\" and + \"global\".""" + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """A value to be used to create a sticky session, which can help getting more consistent results. + As long as the same sessionId is used, a best-effort attempt will be made to target the same + replica set. Be wary that reusing the same sessionID values repeatedly can interfere with the + load balancing of the requests across replicas and adversely affect the performance of the + search service. The value used as sessionId cannot start with a '_' character.""" + scoring_parameters: Optional[list[str]] = rest_field( + name="scoringParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of parameter values to be used in scoring functions (for example, + referencePointParameter) using the format name-values. For example, if the scoring profile + defines a function with a parameter called 'mylocation' the parameter string would be + \"mylocation--122.2,44.8\" (without the quotes).""" + scoring_profile: Optional[str] = rest_field( + name="scoringProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of a scoring profile to evaluate match scores for matching documents in order to sort + the results.""" + debug: Optional[Union[str, "_models.QueryDebugMode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Enables a debugging tool that can be used to further explore your reranked results. Known + values are: \"disabled\", \"semantic\", \"vector\", \"queryRewrites\", \"innerHits\", and + \"all\".""" + search_text: Optional[str] = rest_field(name="search", visibility=["read", "create", "update", "delete", "query"]) + """A full-text search query expression; Use \"*\" or omit this parameter to match all documents.""" + search_fields: Optional[str] = rest_field( + name="searchFields", visibility=["read", "create", "update", "delete", "query"] + ) + """The comma-separated list of field names to which to scope the full-text search. When using + fielded search (fieldName:searchExpression) in a full Lucene query, the field names of each + fielded search expression take precedence over any field names listed in this parameter.""" + search_mode: Optional[Union[str, "_models.SearchMode"]] = rest_field( + name="searchMode", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether any or all of the search terms must be matched in order to count + the document as a match. Known values are: \"any\" and \"all\".""" + query_language: Optional[Union[str, "_models.QueryLanguage"]] = rest_field( + name="queryLanguage", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies the language of the search query. Known values are: \"none\", \"en-us\", + \"en-gb\", \"en-in\", \"en-ca\", \"en-au\", \"fr-fr\", \"fr-ca\", \"de-de\", \"es-es\", + \"es-mx\", \"zh-cn\", \"zh-tw\", \"pt-br\", \"pt-pt\", \"it-it\", \"ja-jp\", \"ko-kr\", + \"ru-ru\", \"cs-cz\", \"nl-be\", \"nl-nl\", \"hu-hu\", \"pl-pl\", \"sv-se\", \"tr-tr\", + \"hi-in\", \"ar-sa\", \"ar-eg\", \"ar-ma\", \"ar-kw\", \"ar-jo\", \"da-dk\", \"no-no\", + \"bg-bg\", \"hr-hr\", \"hr-ba\", \"ms-my\", \"ms-bn\", \"sl-sl\", \"ta-in\", \"vi-vn\", + \"el-gr\", \"ro-ro\", \"is-is\", \"id-id\", \"th-th\", \"lt-lt\", \"uk-ua\", \"lv-lv\", + \"et-ee\", \"ca-es\", \"fi-fi\", \"sr-ba\", \"sr-me\", \"sr-rs\", \"sk-sk\", \"nb-no\", + \"hy-am\", \"bn-in\", \"eu-es\", \"gl-es\", \"gu-in\", \"he-il\", \"ga-ie\", \"kn-in\", + \"ml-in\", \"mr-in\", \"fa-ae\", \"pa-in\", \"te-in\", and \"ur-pk\".""" + speller: Optional[Union[str, "_models.QuerySpellerType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specified the type of the speller to use to spell-correct individual search query + terms. Known values are: \"none\" and \"lexicon\".""" + select: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The comma-separated list of fields to retrieve. If unspecified, all fields marked as + retrievable in the schema are included.""" + skip: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of search results to skip. This value cannot be greater than 100,000. If you need to + scan documents in sequence, but cannot use skip due to this limitation, consider using orderby + on a totally-ordered key and filter with a range query instead.""" + top: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of search results to retrieve. This can be used in conjunction with $skip to + implement client-side paging of search results. If results are truncated due to server-side + paging, the response will include a continuation token that can be used to issue another Search + request for the next page of results.""" + semantic_configuration: Optional[str] = rest_field( + name="semanticConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of a semantic configuration that will be used when processing documents for queries of + type semantic.""" + semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = rest_field( + name="semanticErrorHandling", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows the user to choose whether a semantic call should fail completely (default / current + behavior), or to return partial results. Known values are: \"partial\" and \"fail\".""" + semantic_max_wait_in_milliseconds: Optional[int] = rest_field( + name="semanticMaxWaitInMilliseconds", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows the user to set an upper bound on the amount of time it takes for semantic enrichment to + finish processing before the request fails.""" + semantic_query: Optional[str] = rest_field( + name="semanticQuery", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows setting a separate search query that will be solely used for semantic reranking, + semantic captions and semantic answers. Is useful for scenarios where there is a need to use + different queries between the base retrieval and ranking phase, and the L2 semantic phase.""" + answers: Optional[Union[str, "_models.QueryAnswerType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether answers should be returned as part of the search response. Known + values are: \"none\" and \"extractive\".""" + captions: Optional[Union[str, "_models.QueryCaptionType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether captions should be returned as part of the search response. + Known values are: \"none\" and \"extractive\".""" + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = rest_field( + name="queryRewrites", visibility=["read", "create", "update", "delete", "query"] + ) + """A value that specifies whether query rewrites should be generated to augment the search query. + Known values are: \"none\" and \"generative\".""" + semantic_fields: Optional[str] = rest_field( + name="semanticFields", visibility=["read", "create", "update", "delete", "query"] + ) + """The comma-separated list of field names used for semantic ranking.""" + vector_queries: Optional[list["_models.VectorQuery"]] = rest_field( + name="vectorQueries", visibility=["read", "create", "update", "delete", "query"] + ) + """The query parameters for vector and hybrid search queries.""" + vector_filter_mode: Optional[Union[str, "_models.VectorFilterMode"]] = rest_field( + name="vectorFilterMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether or not filters are applied before or after the vector search is performed. + Default is 'preFilter' for new indexes. Known values are: \"postFilter\", \"preFilter\", and + \"strictPostFilter\".""" + hybrid_search: Optional["_models.HybridSearch"] = rest_field( + name="hybridSearch", visibility=["read", "create", "update", "delete", "query"] + ) + """The query parameters to configure hybrid search behaviors.""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + include_total_result_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, # pylint: disable=redefined-builtin + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + query_type: Optional[Union[str, "_models.QueryType"]] = None, + scoring_statistics: Optional[Union[str, "_models.ScoringStatistics"]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, "_models.QueryDebugMode"]] = None, + search_text: Optional[str] = None, + search_fields: Optional[str] = None, + search_mode: Optional[Union[str, "_models.SearchMode"]] = None, + query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, + speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, + select: Optional[str] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, "_models.QueryAnswerType"]] = None, + captions: Optional[Union[str, "_models.QueryCaptionType"]] = None, + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, + semantic_fields: Optional[str] = None, + vector_queries: Optional[list["_models.VectorQuery"]] = None, + vector_filter_mode: Optional[Union[str, "_models.VectorFilterMode"]] = None, + hybrid_search: Optional["_models.HybridSearch"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchResult(_Model): + """Contains a document found by a search query, plus associated metadata. + + :ivar score: The relevance score of the document compared to other documents returned by the + query. Required. + :vartype score: float + :ivar reranker_score: The relevance score computed by the semantic ranker for the top search + results. Search results are sorted by the RerankerScore first and then by the Score. + RerankerScore is only returned for queries of type 'semantic'. + :vartype reranker_score: float + :ivar reranker_boosted_score: The relevance score computed by boosting the Reranker Score. + Search results are sorted by the RerankerScore/RerankerBoostedScore based on + useScoringProfileBoostedRanking in the Semantic Config. RerankerBoostedScore is only returned + for queries of type 'semantic'. + :vartype reranker_boosted_score: float + :ivar highlights: Text fragments from the document that indicate the matching search terms, + organized by each applicable field; null if hit highlighting was not enabled for the query. + :vartype highlights: dict[str, list[str]] + :ivar captions: Captions are the most representative passages from the document relatively to + the search query. They are often used as document summary. Captions are only returned for + queries of type 'semantic'. + :vartype captions: list[~azure.search.documents.models.QueryCaptionResult] + :ivar document_debug_info: Contains debugging information that can be used to further explore + your search results. + :vartype document_debug_info: list[~azure.search.documents.models.DocumentDebugInfo] + """ + + score: float = rest_field(name="@search.score", visibility=["read", "create", "update", "delete", "query"]) + """The relevance score of the document compared to other documents returned by the query. + Required.""" + reranker_score: Optional[float] = rest_field( + name="@search.rerankerScore", visibility=["read", "create", "update", "delete", "query"] + ) + """The relevance score computed by the semantic ranker for the top search results. Search results + are sorted by the RerankerScore first and then by the Score. RerankerScore is only returned for + queries of type 'semantic'.""" + reranker_boosted_score: Optional[float] = rest_field( + name="@search.rerankerBoostedScore", visibility=["read", "create", "update", "delete", "query"] + ) + """The relevance score computed by boosting the Reranker Score. Search results are sorted by the + RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic + Config. RerankerBoostedScore is only returned for queries of type 'semantic'.""" + highlights: Optional[dict[str, list[str]]] = rest_field( + name="@search.highlights", visibility=["read", "create", "update", "delete", "query"] + ) + """Text fragments from the document that indicate the matching search terms, organized by each + applicable field; null if hit highlighting was not enabled for the query.""" + captions: Optional[list["_models.QueryCaptionResult"]] = rest_field( + name="@search.captions", visibility=["read", "create", "update", "delete", "query"] + ) + """Captions are the most representative passages from the document relatively to the search query. + They are often used as document summary. Captions are only returned for queries of type + 'semantic'.""" + document_debug_info: Optional[list["_models.DocumentDebugInfo"]] = rest_field( + name="@search.documentDebugInfo", visibility=["read"] + ) + """Contains debugging information that can be used to further explore your search results.""" + + @overload + def __init__( + self, + *, + score: float, + reranker_score: Optional[float] = None, + reranker_boosted_score: Optional[float] = None, + highlights: Optional[dict[str, list[str]]] = None, + captions: Optional[list["_models.QueryCaptionResult"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorThreshold(_Model): + """The threshold used for vector queries. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + SearchScoreThreshold, VectorSimilarityThreshold + + :ivar kind: Type of threshold. Required. Known values are: "vectorSimilarity" and + "searchScore". + :vartype kind: str or ~azure.search.documents.models.VectorThresholdKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of threshold. Required. Known values are: \"vectorSimilarity\" and \"searchScore\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SearchScoreThreshold(VectorThreshold, discriminator="searchScore"): + """The results of the vector query will filter based on the '@search.score' value. Note this is + the @search.score returned as part of the search response. The threshold direction will be + chosen for higher @search.score. + + :ivar value: The threshold will filter based on the '@search.score' value. Note this is the + @search.score returned as part of the search response. The threshold direction will be chosen + for higher @search.score. Required. + :vartype value: float + :ivar kind: The kind of threshold used to filter vector queries. Required. The results of the + vector query will filter based on the '@search.score' value. Note this is the @search.score + returned as part of the search response. The threshold direction will be chosen for higher + @search.score. + :vartype kind: str or ~azure.search.documents.models.SEARCH_SCORE + """ + + value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The threshold will filter based on the '@search.score' value. Note this is the @search.score + returned as part of the search response. The threshold direction will be chosen for higher + @search.score. Required.""" + kind: Literal[VectorThresholdKind.SEARCH_SCORE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of threshold used to filter vector queries. Required. The results of the vector query + will filter based on the '@search.score' value. Note this is the @search.score returned as part + of the search response. The threshold direction will be chosen for higher @search.score.""" + + @overload + def __init__( + self, + *, + value: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorThresholdKind.SEARCH_SCORE # type: ignore + + +class SemanticDebugInfo(_Model): + """Contains debugging information specific to semantic ranking requests. + + :ivar title_field: The title field that was sent to the semantic enrichment process, as well as + how it was used. + :vartype title_field: ~azure.search.documents.models.QueryResultDocumentSemanticField + :ivar content_fields: The content fields that were sent to the semantic enrichment process, as + well as how they were used. + :vartype content_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] + :ivar keyword_fields: The keyword fields that were sent to the semantic enrichment process, as + well as how they were used. + :vartype keyword_fields: list[~azure.search.documents.models.QueryResultDocumentSemanticField] + :ivar reranker_input: The raw concatenated strings that were sent to the semantic enrichment + process. + :vartype reranker_input: ~azure.search.documents.models.QueryResultDocumentRerankerInput + """ + + title_field: Optional["_models.QueryResultDocumentSemanticField"] = rest_field( + name="titleField", visibility=["read"] + ) + """The title field that was sent to the semantic enrichment process, as well as how it was used.""" + content_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = rest_field( + name="contentFields", visibility=["read"] + ) + """The content fields that were sent to the semantic enrichment process, as well as how they were + used.""" + keyword_fields: Optional[list["_models.QueryResultDocumentSemanticField"]] = rest_field( + name="keywordFields", visibility=["read"] + ) + """The keyword fields that were sent to the semantic enrichment process, as well as how they were + used.""" + reranker_input: Optional["_models.QueryResultDocumentRerankerInput"] = rest_field( + name="rerankerInput", visibility=["read"] + ) + """The raw concatenated strings that were sent to the semantic enrichment process.""" + + +class SingleVectorFieldResult(_Model): + """A single vector field result. Both @search.score and vector similarity values are returned. + Vector similarity is related to @search.score by an equation. + + :ivar search_score: The @search.score value that is calculated from the vector similarity + score. This is the score that's visible in a pure single-field single-vector query. + :vartype search_score: float + :ivar vector_similarity: The vector similarity score for this document. Note this is the + canonical definition of similarity metric, not the 'distance' version. For example, cosine + similarity instead of cosine distance. + :vartype vector_similarity: float + """ + + search_score: Optional[float] = rest_field(name="searchScore", visibility=["read"]) + """The @search.score value that is calculated from the vector similarity score. This is the score + that's visible in a pure single-field single-vector query.""" + vector_similarity: Optional[float] = rest_field(name="vectorSimilarity", visibility=["read"]) + """The vector similarity score for this document. Note this is the canonical definition of + similarity metric, not the 'distance' version. For example, cosine similarity instead of cosine + distance.""" + + +class SuggestDocumentsResult(_Model): + """Response containing suggestion query results from an index. + + :ivar results: The sequence of results returned by the query. Required. + :vartype results: list[~azure.search.documents.models.SuggestResult] + :ivar coverage: A value indicating the percentage of the index that was included in the query, + or null if minimumCoverage was not set in the request. + :vartype coverage: float + """ + + results: list["_models.SuggestResult"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The sequence of results returned by the query. Required.""" + coverage: Optional[float] = rest_field( + name="@search.coverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating the percentage of the index that was included in the query, or null if + minimumCoverage was not set in the request.""" + + @overload + def __init__( + self, + *, + results: list["_models.SuggestResult"], + coverage: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SuggestRequest(_Model): + """Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors. + + :ivar filter: An OData expression that filters the documents considered for suggestions. + :vartype filter: str + :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestion + query. Default is false. When set to true, the query will find suggestions even if there's a + substituted or missing character in the search text. While this provides a better experience in + some scenarios, it comes at a performance cost as fuzzy suggestion searches are slower and + consume more resources. + :vartype use_fuzzy_matching: bool + :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + :vartype highlight_post_tag: str + :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + :vartype highlight_pre_tag: str + :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a suggestion query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. + :vartype minimum_coverage: float + :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :vartype order_by: str + :ivar search_text: The search text to use to suggest documents. Must be at least 1 character, + and no more than 100 characters. Required. + :vartype search_text: str + :ivar search_fields: The comma-separated list of field names to search for the specified search + text. Target fields must be included in the specified suggester. + :vartype search_fields: str + :ivar select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. + :vartype select: str + :ivar suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :vartype suggester_name: str + :ivar top: The number of suggestions to retrieve. This must be a value between 1 and 100. The + default is 5. + :vartype top: int + """ + + filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An OData expression that filters the documents considered for suggestions.""" + use_fuzzy_matching: Optional[bool] = rest_field( + name="fuzzy", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether to use fuzzy matching for the suggestion query. Default is false. + When set to true, the query will find suggestions even if there's a substituted or missing + character in the search text. While this provides a better experience in some scenarios, it + comes at a performance cost as fuzzy suggestion searches are slower and consume more resources.""" + highlight_post_tag: Optional[str] = rest_field( + name="highlightPostTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, + hit highlighting of suggestions is disabled.""" + highlight_pre_tag: Optional[str] = rest_field( + name="highlightPreTag", visibility=["read", "create", "update", "delete", "query"] + ) + """A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If + omitted, hit highlighting of suggestions is disabled.""" + minimum_coverage: Optional[float] = rest_field( + name="minimumCoverage", visibility=["read", "create", "update", "delete", "query"] + ) + """A number between 0 and 100 indicating the percentage of the index that must be covered by a + suggestion query in order for the query to be reported as a success. This parameter can be + useful for ensuring search availability even for services with only one replica. The default is + 80.""" + order_by: Optional[str] = rest_field(name="orderby", visibility=["read", "create", "update", "delete", "query"]) + """The comma-separated list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses.""" + search_text: str = rest_field(name="search", visibility=["read", "create", "update", "delete", "query"]) + """The search text to use to suggest documents. Must be at least 1 character, and no more than 100 + characters. Required.""" + search_fields: Optional[str] = rest_field( + name="searchFields", visibility=["read", "create", "update", "delete", "query"] + ) + """The comma-separated list of field names to search for the specified search text. Target fields + must be included in the specified suggester.""" + select: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The comma-separated list of fields to retrieve. If unspecified, only the key field will be + included in the results.""" + suggester_name: str = rest_field(name="suggesterName", visibility=["read", "create", "update", "delete", "query"]) + """The name of the suggester as specified in the suggesters collection that's part of the index + definition. Required.""" + top: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of suggestions to retrieve. This must be a value between 1 and 100. The default is + 5.""" + + @overload + def __init__( + self, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, # pylint: disable=redefined-builtin + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SuggestResult(_Model): + """A result containing a document found by a suggestion query, plus associated metadata. + + :ivar text: The text of the suggestion result. Required. + :vartype text: str + """ + + text: str = rest_field(name="@search.text", visibility=["read", "create", "update", "delete", "query"]) + """The text of the suggestion result. Required.""" + + @overload + def __init__( + self, + *, + text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TextResult(_Model): + """The BM25 or Classic score for the text portion of the query. + + :ivar search_score: The BM25 or Classic score for the text portion of the query. + :vartype search_score: float + """ + + search_score: Optional[float] = rest_field(name="searchScore", visibility=["read"]) + """The BM25 or Classic score for the text portion of the query.""" + + +class VectorQuery(_Model): + """The query parameters for vector and hybrid search queries. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + VectorizableImageBinaryQuery, VectorizableImageUrlQuery, VectorizableTextQuery, VectorizedQuery + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector + query. If no filter expression is defined at the vector level, the expression defined in the + top level filter parameter is used instead. + :vartype per_document_vector_limit: int + :ivar kind: Type of query. Required. Known values are: "vector", "text", "imageUrl", and + "imageBinary". + :vartype kind: str or ~azure.search.documents.models.VectorQueryKind + """ + + __mapping__: dict[str, _Model] = {} + k_nearest_neighbors: Optional[int] = rest_field( + name="k", visibility=["read", "create", "update", "delete", "query"] + ) + """Number of nearest neighbors to return as top hits.""" + fields: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Vector Fields of type Collection(Edm.Single) to be included in the vector searched.""" + exhaustive: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """When true, triggers an exhaustive k-nearest neighbor search across all vectors within the + vector index. Useful for scenarios where exact matches are critical, such as determining ground + truth values.""" + oversampling: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Oversampling factor. Minimum value is 1. It overrides the 'defaultOversampling' parameter + configured in the index definition. It can be set only when 'rerankWithOriginalVectors' is + true. This parameter is only permitted when a compression method is used on the underlying + vector field.""" + weight: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Relative weight of the vector query when compared to other vector query and/or the text query + within the same search request. This value is used when combining the results of multiple + ranking lists produced by the different vector queries and/or the results retrieved through the + text query. The higher the weight, the higher the documents that matched that query will be in + the final ranking. Default is 1.0 and the value needs to be a positive number larger than zero.""" + threshold: Optional["_models.VectorThreshold"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The threshold used for vector queries. Note this can only be set if all 'fields' use the same + similarity metric.""" + filter_override: Optional[str] = rest_field( + name="filterOverride", visibility=["read", "create", "update", "delete", "query"] + ) + """The OData filter expression to apply to this specific vector query. If no filter expression is + defined at the vector level, the expression defined in the top level filter parameter is used + instead.""" + per_document_vector_limit: Optional[int] = rest_field( + name="perDocumentVectorLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """The OData filter expression to apply to this specific vector query. If no filter expression is + defined at the vector level, the expression defined in the top level filter parameter is used + instead.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Type of query. Required. Known values are: \"vector\", \"text\", \"imageUrl\", and + \"imageBinary\".""" + + @overload + def __init__( + self, + *, + kind: str, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VectorizableImageBinaryQuery(VectorQuery, discriminator="imageBinary"): + """The query parameters to use for vector search when a base 64 encoded binary of an image that + needs to be vectorized is provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector + query. If no filter expression is defined at the vector level, the expression defined in the + top level filter parameter is used instead. + :vartype per_document_vector_limit: int + :ivar base64_image: The base 64 encoded binary of an image to be vectorized to perform a vector + search query. + :vartype base64_image: str + :ivar kind: The kind of vector query being performed. Required. Vector query where a base 64 + encoded binary of an image that needs to be vectorized is provided. + :vartype kind: str or ~azure.search.documents.models.IMAGE_BINARY + """ + + base64_image: Optional[str] = rest_field( + name="base64Image", visibility=["read", "create", "update", "delete", "query"] + ) + """The base 64 encoded binary of an image to be vectorized to perform a vector search query.""" + kind: Literal[VectorQueryKind.IMAGE_BINARY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where a base 64 encoded binary + of an image that needs to be vectorized is provided.""" + + @overload + def __init__( + self, + *, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + base64_image: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.IMAGE_BINARY # type: ignore + + +class VectorizableImageUrlQuery(VectorQuery, discriminator="imageUrl"): + """The query parameters to use for vector search when an url that represents an image value that + needs to be vectorized is provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector + query. If no filter expression is defined at the vector level, the expression defined in the + top level filter parameter is used instead. + :vartype per_document_vector_limit: int + :ivar url: The URL of an image to be vectorized to perform a vector search query. + :vartype url: str + :ivar kind: The kind of vector query being performed. Required. Vector query where an url that + represents an image value that needs to be vectorized is provided. + :vartype kind: str or ~azure.search.documents.models.IMAGE_URL + """ + + url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URL of an image to be vectorized to perform a vector search query.""" + kind: Literal[VectorQueryKind.IMAGE_URL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where an url that represents + an image value that needs to be vectorized is provided.""" + + @overload + def __init__( + self, + *, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.IMAGE_URL # type: ignore + + +class VectorizableTextQuery(VectorQuery, discriminator="text"): + """The query parameters to use for vector search when a text value that needs to be vectorized is + provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector + query. If no filter expression is defined at the vector level, the expression defined in the + top level filter parameter is used instead. + :vartype per_document_vector_limit: int + :ivar text: The text to be vectorized to perform a vector search query. Required. + :vartype text: str + :ivar query_rewrites: Can be configured to let a generative model rewrite the query before + sending it to be vectorized. Known values are: "none" and "generative". + :vartype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :ivar kind: The kind of vector query being performed. Required. Vector query where a text value + that needs to be vectorized is provided. + :vartype kind: str or ~azure.search.documents.models.TEXT + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The text to be vectorized to perform a vector search query. Required.""" + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = rest_field( + name="queryRewrites", visibility=["read", "create", "update", "delete", "query"] + ) + """Can be configured to let a generative model rewrite the query before sending it to be + vectorized. Known values are: \"none\" and \"generative\".""" + kind: Literal[VectorQueryKind.TEXT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where a text value that needs + to be vectorized is provided.""" + + @overload + def __init__( + self, + *, + text: str, + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + query_rewrites: Optional[Union[str, "_models.QueryRewritesType"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.TEXT # type: ignore + + +class VectorizedQuery(VectorQuery, discriminator="vector"): + """The query parameters to use for vector search when a raw vector value is provided. + + :ivar k_nearest_neighbors: Number of nearest neighbors to return as top hits. + :vartype k_nearest_neighbors: int + :ivar fields: Vector Fields of type Collection(Edm.Single) to be included in the vector + searched. + :vartype fields: str + :ivar exhaustive: When true, triggers an exhaustive k-nearest neighbor search across all + vectors within the vector index. Useful for scenarios where exact matches are critical, such as + determining ground truth values. + :vartype exhaustive: bool + :ivar oversampling: Oversampling factor. Minimum value is 1. It overrides the + 'defaultOversampling' parameter configured in the index definition. It can be set only when + 'rerankWithOriginalVectors' is true. This parameter is only permitted when a compression method + is used on the underlying vector field. + :vartype oversampling: float + :ivar weight: Relative weight of the vector query when compared to other vector query and/or + the text query within the same search request. This value is used when combining the results of + multiple ranking lists produced by the different vector queries and/or the results retrieved + through the text query. The higher the weight, the higher the documents that matched that query + will be in the final ranking. Default is 1.0 and the value needs to be a positive number larger + than zero. + :vartype weight: float + :ivar threshold: The threshold used for vector queries. Note this can only be set if all + 'fields' use the same similarity metric. + :vartype threshold: ~azure.search.documents.models.VectorThreshold + :ivar filter_override: The OData filter expression to apply to this specific vector query. If + no filter expression is defined at the vector level, the expression defined in the top level + filter parameter is used instead. + :vartype filter_override: str + :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector + query. If no filter expression is defined at the vector level, the expression defined in the + top level filter parameter is used instead. + :vartype per_document_vector_limit: int + :ivar vector: The vector representation of a search query. Required. + :vartype vector: list[float] + :ivar kind: The kind of vector query being performed. Required. Vector query where a raw vector + value is provided. + :vartype kind: str or ~azure.search.documents.models.VECTOR + """ + + vector: list[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The vector representation of a search query. Required.""" + kind: Literal[VectorQueryKind.VECTOR] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of vector query being performed. Required. Vector query where a raw vector value is + provided.""" + + @overload + def __init__( + self, + *, + vector: list[float], + k_nearest_neighbors: Optional[int] = None, + fields: Optional[str] = None, + exhaustive: Optional[bool] = None, + oversampling: Optional[float] = None, + weight: Optional[float] = None, + threshold: Optional["_models.VectorThreshold"] = None, + filter_override: Optional[str] = None, + per_document_vector_limit: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorQueryKind.VECTOR # type: ignore + + +class VectorsDebugInfo(_Model): + """ "Contains debugging information specific to vector and hybrid search."). + + :ivar subscores: The breakdown of subscores of the document prior to the chosen result set + fusion/combination method such as RRF. + :vartype subscores: ~azure.search.documents.models.QueryResultDocumentSubscores + """ + + subscores: Optional["_models.QueryResultDocumentSubscores"] = rest_field(visibility=["read"]) + """The breakdown of subscores of the document prior to the chosen result set fusion/combination + method such as RRF.""" + + +class VectorSimilarityThreshold(VectorThreshold, discriminator="vectorSimilarity"): + """The results of the vector query will be filtered based on the vector similarity metric. Note + this is the canonical definition of similarity metric, not the 'distance' version. The + threshold direction (larger or smaller) will be chosen automatically according to the metric + used by the field. + + :ivar value: The threshold will filter based on the similarity metric value. Note this is the + canonical definition of similarity metric, not the 'distance' version. The threshold direction + (larger or smaller) will be chosen automatically according to the metric used by the field. + Required. + :vartype value: float + :ivar kind: The kind of threshold used to filter vector queries. Required. The results of the + vector query will be filtered based on the vector similarity metric. Note this is the canonical + definition of similarity metric, not the 'distance' version. The threshold direction (larger or + smaller) will be chosen automatically according to the metric used by the field. + :vartype kind: str or ~azure.search.documents.models.VECTOR_SIMILARITY + """ + + value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The threshold will filter based on the similarity metric value. Note this is the canonical + definition of similarity metric, not the 'distance' version. The threshold direction (larger or + smaller) will be chosen automatically according to the metric used by the field. Required.""" + kind: Literal[VectorThresholdKind.VECTOR_SIMILARITY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of threshold used to filter vector queries. Required. The results of the vector query + will be filtered based on the vector similarity metric. Note this is the canonical definition + of similarity metric, not the 'distance' version. The threshold direction (larger or smaller) + will be chosen automatically according to the metric used by the field.""" + + @overload + def __init__( + self, + *, + value: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = VectorThresholdKind.VECTOR_SIMILARITY # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/models/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/operations/__init__.py similarity index 70% rename from sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/operations/__init__.py index de96b0faddf2..e7e958355b4b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/operations/__init__.py @@ -1,6 +1,8 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -10,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._documents_operations import DocumentsOperations # type: ignore +from ._operations import DocumentsOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * diff --git a/sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py new file mode 100644 index 000000000000..74358c90b5ca --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py @@ -0,0 +1,1826 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1 +from .._configuration import SearchClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer +from .._validation import api_version_validation + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_documents_count_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "text/plain") + + # Construct URL + _url = "/indexes('{indexName}')/docs/$count" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_search_get_request( + index_name: str, + *, + search_text: Optional[str] = None, + include_total_result_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[List[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + search_fields: Optional[List[str]] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + select: Optional[List[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + semantic_query: Optional[str] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + semantic_fields: Optional[List[str]] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if search_text is not None: + _params["search"] = _SERIALIZER.query("search_text", search_text, "str") + if include_total_result_count is not None: + _params["$count"] = _SERIALIZER.query("include_total_result_count", include_total_result_count, "bool") + if facets is not None: + _params["facet"] = [_SERIALIZER.query("facets", q, "str") if q is not None else "" for q in facets] + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if highlight_fields is not None: + _params["highlight"] = _SERIALIZER.query("highlight_fields", highlight_fields, "[str]", div=",") + if highlight_post_tag is not None: + _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") + if highlight_pre_tag is not None: + _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") + if minimum_coverage is not None: + _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") + if query_type is not None: + _params["queryType"] = _SERIALIZER.query("query_type", query_type, "str") + if scoring_parameters is not None: + _params["scoringParameter"] = [ + _SERIALIZER.query("scoring_parameters", q, "str") if q is not None else "" for q in scoring_parameters + ] + if scoring_profile is not None: + _params["scoringProfile"] = _SERIALIZER.query("scoring_profile", scoring_profile, "str") + if search_fields is not None: + _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") + if search_mode is not None: + _params["searchMode"] = _SERIALIZER.query("search_mode", search_mode, "str") + if scoring_statistics is not None: + _params["scoringStatistics"] = _SERIALIZER.query("scoring_statistics", scoring_statistics, "str") + if session_id is not None: + _params["sessionId"] = _SERIALIZER.query("session_id", session_id, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + if skip is not None: + _params["$skip"] = _SERIALIZER.query("skip", skip, "int") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if semantic_configuration is not None: + _params["semanticConfiguration"] = _SERIALIZER.query("semantic_configuration", semantic_configuration, "str") + if semantic_error_handling is not None: + _params["semanticErrorHandling"] = _SERIALIZER.query("semantic_error_handling", semantic_error_handling, "str") + if semantic_max_wait_in_milliseconds is not None: + _params["semanticMaxWaitInMilliseconds"] = _SERIALIZER.query( + "semantic_max_wait_in_milliseconds", semantic_max_wait_in_milliseconds, "int" + ) + if answers is not None: + _params["answers"] = _SERIALIZER.query("answers", answers, "str") + if captions is not None: + _params["captions"] = _SERIALIZER.query("captions", captions, "str") + if semantic_query is not None: + _params["semanticQuery"] = _SERIALIZER.query("semantic_query", semantic_query, "str") + if query_rewrites is not None: + _params["queryRewrites"] = _SERIALIZER.query("query_rewrites", query_rewrites, "str") + if debug is not None: + _params["debug"] = _SERIALIZER.query("debug", debug, "str") + if query_language is not None: + _params["queryLanguage"] = _SERIALIZER.query("query_language", query_language, "str") + if speller is not None: + _params["speller"] = _SERIALIZER.query("speller", speller, "str") + if semantic_fields is not None: + _params["semanticFields"] = _SERIALIZER.query("semantic_fields", semantic_fields, "[str]", div=",") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_search_post_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.post.search" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_get_request( + key: str, + index_name: str, + *, + selected_fields: Optional[List[str]] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs('{key}')" + path_format_arguments = { + "key": _SERIALIZER.url("key", key, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if selected_fields is not None: + _params["$select"] = _SERIALIZER.query("selected_fields", selected_fields, "[str]", div=",") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_suggest_get_request( + index_name: str, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + search_fields: Optional[List[str]] = None, + select: Optional[List[str]] = None, + top: Optional[int] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.suggest" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["search"] = _SERIALIZER.query("search_text", search_text, "str") + _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if use_fuzzy_matching is not None: + _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") + if highlight_post_tag is not None: + _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") + if highlight_pre_tag is not None: + _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") + if minimum_coverage is not None: + _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "[str]", div=",") + if search_fields is not None: + _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_suggest_post_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.post.suggest" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_index_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.index" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_autocomplete_get_request( + index_name: str, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[List[str]] = None, + top: Optional[int] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.autocomplete" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["search"] = _SERIALIZER.query("search_text", search_text, "str") + _params["suggesterName"] = _SERIALIZER.query("suggester_name", suggester_name, "str") + if autocomplete_mode is not None: + _params["autocompleteMode"] = _SERIALIZER.query("autocomplete_mode", autocomplete_mode, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if use_fuzzy_matching is not None: + _params["fuzzy"] = _SERIALIZER.query("use_fuzzy_matching", use_fuzzy_matching, "bool") + if highlight_post_tag is not None: + _params["highlightPostTag"] = _SERIALIZER.query("highlight_post_tag", highlight_post_tag, "str") + if highlight_pre_tag is not None: + _params["highlightPreTag"] = _SERIALIZER.query("highlight_pre_tag", highlight_pre_tag, "str") + if minimum_coverage is not None: + _params["minimumCoverage"] = _SERIALIZER.query("minimum_coverage", minimum_coverage, "float") + if search_fields is not None: + _params["searchFields"] = _SERIALIZER.query("search_fields", search_fields, "[str]", div=",") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_documents_autocomplete_post_request( # pylint: disable=name-too-long + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/indexes('{indexName}')/docs/search.post.autocomplete" + path_format_arguments = { + "indexName": _SERIALIZER.url("index_name", index_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class DocumentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.search.documents.SearchClient`'s + :attr:`documents` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SearchClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def count(self, *, query_source_authorization: Optional[str] = None, **kwargs: Any) -> int: + """Queries the number of documents in the index. + + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: int + :rtype: int + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[int] = kwargs.pop("cls", None) + + _request = build_documents_count_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(int, response.text()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + params_added_on={ + "2025-08-01-preview": ["query_rewrites", "debug", "query_language", "speller", "semantic_fields"] + }, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + def search_get( + self, + *, + search_text: Optional[str] = None, + include_total_result_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[List[str]] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + search_fields: Optional[List[str]] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + select: Optional[List[str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + semantic_query: Optional[str] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + semantic_fields: Optional[List[str]] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword include_total_result_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_result_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The list of field names to use for hit highlights. Only searchable + fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: list[str] + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword search_fields: The list of field names to which to scope the full-text search. When + using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of + each fielded search expression take precedence over any field names listed in this parameter. + Default value is None. + :paramtype search_fields: list[str] + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. Known values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help to get more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as + retrievable in the schema are included. Default value is None. + :paramtype select: list[str] + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + Default value is None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration: The name of the semantic configuration that lists which fields + should be used for semantic ranking, captions, highlights, and answers. Default value is None. + :paramtype semantic_configuration: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely, or to return partial results (default). Known values are: "partial" and "fail". + Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword answers: This parameter is only valid if the query type is ``semantic``. If set, the + query returns answers extracted from key passages in the highest ranked documents. The number + of answers returned can be configured by appending the pipe character ``|`` followed by the + ``count-`` option after the answers parameter value, such as + ``extractive|count-3``. Default count is 1. The confidence threshold can be configured by + appending the pipe character ``|`` followed by the ``threshold-`` option + after the answers parameter value, such as ``extractive|threshold-0.9``. Default threshold is + 0.7. The maximum character length of answers can be configured by appending the pipe character + '|' followed by the 'count-', such as + 'extractive|maxcharlength-600'. Known values are: "none" and "extractive". Default value is + None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: This parameter is only valid if the query type is ``semantic``. If set, the + query returns captions extracted from key passages in the highest ranked documents. When + Captions is set to ``extractive``, highlighting is enabled by default, and can be configured by + appending the pipe character ``|`` followed by the ``highlight-`` option, such as + ``extractive|highlight-true``. Defaults to ``None``. The maximum character length of captions + can be configured by appending the pipe character '|' followed by the 'count-', such as 'extractive|maxcharlength-600'. Known values are: "none" and + "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword query_rewrites: When QueryRewrites is set to ``generative``, the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword debug: Enables a debugging tool that can be used to further explore your search + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword query_language: The language of the query. Known values are: "none", "en-us", "en-gb", + "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", + "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", + "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", + "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", "fi-fi", + "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", "gu-in", + "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". Default + value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword speller: Improve search recall by spell-correcting individual search query terms. + Known values are: "none" and "lexicon". Default value is None. + :paramtype speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword semantic_fields: The list of field names used for semantic ranking. Default value is + None. + :paramtype semantic_fields: list[str] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchDocumentsResult] = kwargs.pop("cls", None) + + _request = build_documents_search_get_request( + index_name=self._config.index_name, + search_text=search_text, + include_total_result_count=include_total_result_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + search_fields=search_fields, + search_mode=search_mode, + scoring_statistics=scoring_statistics, + session_id=session_id, + select=select, + skip=skip, + top=top, + semantic_configuration=semantic_configuration, + semantic_error_handling=semantic_error_handling, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + answers=answers, + captions=captions, + semantic_query=semantic_query, + query_rewrites=query_rewrites, + debug=debug, + query_language=query_language, + speller=speller, + semantic_fields=semantic_fields, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def search_post( + self, + search_request: _models1.SearchRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Required. + :type search_request: ~azure.search.documents.models.SearchRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def search_post( + self, + search_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Required. + :type search_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def search_post( + self, + search_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Required. + :type search_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def search_post( + self, + search_request: Union[_models1.SearchRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.SearchDocumentsResult: + """Searches for documents in the index. + + :param search_request: The definition of the Search request. Is one of the following types: + SearchRequest, JSON, IO[bytes] Required. + :type search_request: ~azure.search.documents.models.SearchRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SearchDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(search_request, (IOBase, bytes)): + _content = search_request + else: + _content = json.dumps(search_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_search_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get( + self, + key: str, + *, + selected_fields: Optional[List[str]] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.LookupDocument: + """Retrieves a document from the index. + + :param key: The key of the document to retrieve. Required. + :type key: str + :keyword selected_fields: List of field names to retrieve for the document; Any field not + retrieved will be missing from the returned document. Default value is None. + :paramtype selected_fields: list[str] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: LookupDocument. The LookupDocument is compatible with MutableMapping + :rtype: ~azure.search.documents.models.LookupDocument + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.LookupDocument] = kwargs.pop("cls", None) + + _request = build_documents_get_request( + key=key, + index_name=self._config.index_name, + selected_fields=selected_fields, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.LookupDocument, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def suggest_get( + self, + *, + search_text: str, + suggester_name: str, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[List[str]] = None, + search_fields: Optional[List[str]] = None, + select: Optional[List[str]] = None, + top: Optional[int] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestions query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestions queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestions query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, or desc + to indicate descending. The default is ascending order. Ties will be broken by the match scores + of documents. If no $orderby is specified, the default sort order is descending by document + match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: list[str] + :keyword search_fields: The list of field names to search for the specified search text. Target + fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword select: The list of fields to retrieve. If unspecified, only the key field will be + included in the results. Default value is None. + :paramtype select: list[str] + :keyword top: The number of suggestions to retrieve. The value must be a number between 1 and + 100. The default is 5. Default value is None. + :paramtype top: int + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SuggestDocumentsResult] = kwargs.pop("cls", None) + + _request = build_documents_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SuggestDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def suggest_post( + self, + suggest_request: _models1.SuggestRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Required. + :type suggest_request: ~azure.search.documents.models.SuggestRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def suggest_post( + self, + suggest_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Required. + :type suggest_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def suggest_post( + self, + suggest_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Required. + :type suggest_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def suggest_post( + self, + suggest_request: Union[_models1.SuggestRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.SuggestDocumentsResult: + """Suggests documents in the index that match the given partial query text. + + :param suggest_request: The Suggest request. Is one of the following types: SuggestRequest, + JSON, IO[bytes] Required. + :type suggest_request: ~azure.search.documents.models.SuggestRequest or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SuggestDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(suggest_request, (IOBase, bytes)): + _content = suggest_request + else: + _content = json.dumps(suggest_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_suggest_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SuggestDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def index( + self, + batch: _models1.IndexBatch, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Required. + :type batch: ~azure.search.documents.models.IndexBatch + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def index( + self, + batch: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Required. + :type batch: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def index( + self, + batch: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Required. + :type batch: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def index( + self, + batch: Union[_models1.IndexBatch, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.IndexDocumentsResult: + """Sends a batch of document write actions to the index. + + :param batch: The batch of index actions. Is one of the following types: IndexBatch, JSON, + IO[bytes] Required. + :type batch: ~azure.search.documents.models.IndexBatch or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.IndexDocumentsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.IndexDocumentsResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(batch, (IOBase, bytes)): + _content = batch + else: + _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_index_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 207]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.IndexDocumentsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def autocomplete_get( + self, + *, + search_text: str, + suggester_name: str, + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[List[str]] = None, + top: Optional[int] = None, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :keyword search_text: The incomplete term which should be auto-completed. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The list of field names to consider when querying for auto-completed + terms. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: list[str] + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.AutocompleteResult] = kwargs.pop("cls", None) + + _request = build_documents_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.AutocompleteResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def autocomplete_post( + self, + autocomplete_request: _models1.AutocompleteRequest, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Required. + :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def autocomplete_post( + self, + autocomplete_request: JSON, + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Required. + :type autocomplete_request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def autocomplete_post( + self, + autocomplete_request: IO[bytes], + *, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models1.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Required. + :type autocomplete_request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def autocomplete_post( + self, + autocomplete_request: Union[_models1.AutocompleteRequest, JSON, IO[bytes]], + *, + query_source_authorization: Optional[str] = None, + **kwargs: Any + ) -> _models1.AutocompleteResult: + """Autocompletes incomplete query terms based on input text and matching terms in the index. + + :param autocomplete_request: The definition of the Autocomplete request. Is one of the + following types: AutocompleteRequest, JSON, IO[bytes] Required. + :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or JSON or + IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models.AutocompleteResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.AutocompleteResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(autocomplete_request, (IOBase, bytes)): + _content = autocomplete_request + else: + _content = json.dumps(autocomplete_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_documents_autocomplete_post_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.AutocompleteResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/py.typed b/sdk/search/azure-search-documents/azure/search/documents/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/py.typed +++ b/sdk/search/azure-search-documents/azure/search/documents/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/search/azure-search-documents/samples/README.md b/sdk/search/azure-search-documents/samples/README.md deleted file mode 100644 index 9a658a5cd783..000000000000 --- a/sdk/search/azure-search-documents/samples/README.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -page_type: sample -languages: - - python -products: - - azure - - azure-search ---- - -# Samples for Azure Cognitive Search client library for Python - -These code samples show common scenario operations with the Azure Cognitive -Search client library. - -Authenticate the client with a Azure Cognitive Search [API Key Credential](https://learn.microsoft.com/azure/search/search-security-api-keys): - -[https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/search/azure-search-documents/samples/sample_authentication.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_authentication.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py)) - -Then for common search index operations: - -* Get a document by key: [sample_get_document.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_get_document.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py)) - -* Perform a simple text query: [sample_simple_query.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_simple_query.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py)) - -* Perform a filtered query: [sample_filter_query.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_filter_query.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py)) - -* Perform a faceted query: [sample_facet_query.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_facet_query.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py)) - -* Get auto-completions: [sample_autocomplete.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_autocomplete.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py)) - -* Get search suggestions: [sample_suggestions.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_suggestions.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py)) - -* Perform basic document updates: [sample_crud_operations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_crud_operations.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py)) - -* CRUD operations for index: [sample_index_crud_operations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py)) - -* Analyze text: [sample_analyze_text.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_analyze_text.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py)) - -* CRUD operations for indexers: [sample_indexers_operations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_indexers_operations.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py)) - -* General workflow of indexer, datasource and index: [sample_indexer_datasource_skillset.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py) - -* Semantic search: [sample_semantic_search.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_semantic_search.py) - -* Vector search: [sample_vector_search.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_vector_search.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py)) - -## Prerequisites - -* Python 3.8 or later is required to use this package -* You must have an [Azure subscription](https://azure.microsoft.com/free/) -* You must create the "Hotels" sample index [in the Azure Portal](https://learn.microsoft.com/azure/search/search-get-started-portal) - -## Setup - -1. Install the Azure Cognitive Search client library for Python with [pip](https://pypi.org/project/pip/): - - ```bash - pip install azure-search-documents --pre - ``` - -2. Clone or download [this repository](https://github.com/Azure/azure-sdk-for-python) -3. Open this sample folder in [Visual Studio Code](https://code.visualstudio.com) or your IDE of choice. - -## Running the samples - -1. Open a terminal window and `cd` to the directory that the samples are saved in. -2. Set the environment variables specified in the sample file you wish to run. -3. Follow the usage described in the file, e.g. `python sample_simple_query.py` - -## Next steps - -Check out the [API reference documentation](https://learn.microsoft.com/rest/api/searchservice/) -to learn more about what you can do with the Azure Cognitive Search client library. diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py deleted file mode 100644 index a20a4d5cc4af..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_analyze_text_async.py -DESCRIPTION: - This sample demonstrates how to analyze text. -USAGE: - python sample_analyze_text_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def simple_analyze_text(): - # [START simple_analyze_text_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.indexes.aio import SearchIndexClient - from azure.search.documents.indexes.models import AnalyzeTextOptions - - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - - analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") - - async with client: - result = await client.analyze_text(index_name, analyze_request) - print(result.as_dict()) - # [END simple_analyze_text_async] - - -if __name__ == "__main__": - asyncio.run(simple_analyze_text()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py deleted file mode 100644 index e4340c96274c..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_authentication_async.py -DESCRIPTION: - This sample demonstrates how to authenticate with the Azure Congnitive Search - service with an API key. See more details about authentication here: - https://learn.microsoft.com/azure.search.documents/search-security-api-keys -USAGE: - python sample_authentication_async.py - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import asyncio -import os - - -async def authentication_with_api_key_credential_async(): - # [START create_search_client_with_key_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - # [END create_search_client_with_key_async] - - async with search_client: - result = await search_client.get_document_count() - - print("There are {} documents in the {} search index.".format(result, index_name)) - - -async def authentication_service_client_with_api_key_credential_async(): - # [START create_search_service_with_key_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.indexes.aio import SearchIndexClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - # [END create_search_service_with_key_async] - - -async def authentication_with_aad(): - # [START authentication_with_aad] - from azure.identity.aio import DefaultAzureCredential - from azure.search.documents.aio import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - credential = DefaultAzureCredential() - - search_client = SearchClient(service_endpoint, index_name, credential) - # [END authentication_with_aad] - - async with search_client: - result = await search_client.get_document_count() - - print("There are {} documents in the {} search index.".format(result, index_name)) - - -async def authentication_service_client_with_aad(): - # [START authentication_service_client_with_aad] - from azure.identity.aio import DefaultAzureCredential - from azure.search.documents.indexes.aio import SearchIndexClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - credential = DefaultAzureCredential() - - client = SearchIndexClient(service_endpoint, credential) - # [END authentication_service_client_with_aad] - - -if __name__ == "__main__": - asyncio.run(authentication_with_api_key_credential_async()) - asyncio.run(authentication_service_client_with_api_key_credential_async()) - asyncio.run(authentication_with_aad()) - asyncio.run(authentication_service_client_with_aad()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py deleted file mode 100644 index 856652212a40..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_autocomplete_async.py -DESCRIPTION: - This sample demonstrates how to obtain autocompletion suggestions from an - Azure search index. -USAGE: - python sample_autocomplete_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def autocomplete_query(): - # [START autocomplete_query_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - results = await search_client.autocomplete(search_text="bo", suggester_name="sg") - - print("Autocomplete suggestions for 'bo'") - for result in results: - print(" Completion: {}".format(result["text"])) - # [END autocomplete_query_async] - - -if __name__ == "__main__": - asyncio.run(autocomplete_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py deleted file mode 100644 index 23b9aeae146c..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_batch_client_async.py -DESCRIPTION: - This sample demonstrates how to upload, merge, or delete documents using SearchIndexingBufferedSender. -USAGE: - python sample_batch_client_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.aio import SearchIndexingBufferedSender - - -async def sample_batching_client(): - DOCUMENT = { - "category": "Hotel", - "hotelId": "1000", - "rating": 4.0, - "rooms": [], - "hotelName": "Azure Inn", - } - - async with SearchIndexingBufferedSender(service_endpoint, index_name, AzureKeyCredential(key)) as batch_client: - # add upload actions - await batch_client.upload_documents(documents=[DOCUMENT]) - # add merge actions - await batch_client.merge_documents(documents=[{"hotelId": "1000", "rating": 4.5}]) - # add delete actions - await batch_client.delete_documents(documents=[{"hotelId": "1000"}]) - - -async def main(): - await sample_batching_client() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py deleted file mode 100644 index 697d8d03ae10..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py +++ /dev/null @@ -1,73 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_crud_operations_async.py -DESCRIPTION: - This sample demonstrates how to upload, merge, or delete documents from an - Azure Search index. -USAGE: - python sample_crud_operations_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.aio import SearchClient - -search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - -async def upload_document(): - # [START upload_document_async] - DOCUMENT = { - "hotelId": "1000", - "hotelName": "Azure Inn", - } - - result = await search_client.upload_documents(documents=[DOCUMENT]) - - print("Upload of new document succeeded: {}".format(result[0].succeeded)) - # [END upload_document_async] - - -async def merge_document(): - # [START merge_document_async] - result = await search_client.upload_documents(documents=[{"hotelId": "783", "hotelName": "Renovated Ranch"}]) - - print("Merge into new document succeeded: {}".format(result[0].succeeded)) - # [END merge_document_async] - - -async def delete_document(): - # [START delete_document_async] - result = await search_client.upload_documents(documents=[{"hotelId": "1000"}]) - - print("Delete new document succeeded: {}".format(result[0].succeeded)) - # [END delete_document_async] - - -async def main(): - await upload_document() - await merge_document() - await delete_document() - await search_client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py deleted file mode 100644 index fd39b24abbe8..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_data_source_operations_async.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete a Data Source. -USAGE: - python sample_data_source_operations_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - -import asyncio -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] -connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.models import SearchIndexerDataContainer, SearchIndexerDataSourceConnection -from azure.search.documents.indexes.aio import SearchIndexerClient - -client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - - -async def create_data_source_connection(): - # [START create_data_source_connection_async] - container = SearchIndexerDataContainer(name="searchcontainer") - data_source = SearchIndexerDataSourceConnection( - name="async-sample-data-source-connection", - type="azureblob", - connection_string=connection_string, - container=container, - ) - result = await client.create_data_source_connection(data_source) - print("Create new Data Source Connection - async-sample-data-source-connection") - # [END create_data_source_connection_async] - - -async def list_data_source_connections(): - # [START list_data_source_connection_async] - result = await client.get_data_source_connections() - names = [x.name for x in result] - print("Found {} Data Source Connections in the service: {}".format(len(result), ", ".join(names))) - # [END list_data_source_connection_async] - - -async def get_data_source_connection(): - # [START get_data_source_connection_async] - result = await client.get_data_source_connection("async-sample-data-source-connection") - print("Retrived Data Source Connection 'async-sample-data-source-connection'") - return result - # [END get_data_source_connection_async] - - -async def delete_data_source_connection(): - # [START delete_data_source_connection_async] - await client.delete_data_source_connection("async-sample-data-source-connection") - print("Data Source Connection 'async-sample-data-source-connection' successfully deleted") - # [END delete_data_source_connection_async] - - -async def main(): - await create_data_source_connection() - await list_data_source_connections() - await get_data_source_connection() - await delete_data_source_connection() - await client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py deleted file mode 100644 index 1ce8666eabbd..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_facet_query_async.py -DESCRIPTION: - This sample demonstrates how to obtain search facets on specified field in - an Azure Search index. -USAGE: - python sample_facet_query_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -from typing import List, Dict, cast -import os -import asyncio - - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def filter_query(): - # [START facet_query_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - results = await search_client.search(search_text="WiFi", facets=["category,count:3", "parkingIncluded"]) - - facets: Dict[str, List[str]] = cast(Dict[str, List[str]], await results.get_facets()) - - print("Catgory facet counts for hotels:") - for facet in facets["category"]: - print(" {}".format(facet)) - # [END facet_query_async] - - -if __name__ == "__main__": - asyncio.run(filter_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py deleted file mode 100644 index e8dc44bda617..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_filter_query_async.py -DESCRIPTION: - This sample demonstrates how search results from an Azure Search index can - be filtered and ordered. -USAGE: - python sample_filter_query_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def filter_query(): - # [START filter_query_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - results = await search_client.search( - search_text="WiFi", - filter="Address/StateProvince eq 'FL' and Address/Country eq 'USA'", - select=["hotelName", "rating"], - order_by=["rating desc"], - ) - - print("Florida hotels containing 'WiFi', sorted by Rating:") - async for result in results: - print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) - # [END filter_query_async] - - -if __name__ == "__main__": - asyncio.run(filter_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py deleted file mode 100644 index c9b177bef4eb..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_get_document_async.py -DESCRIPTION: - This sample demonstrates how to retrieve a specific document by key from an - Azure Search index. -USAGE: - python sample_get_document_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def autocomplete_query(): - # [START get_document_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - result = await search_client.get_document(key="23") - - print("Details for hotel '23' are:") - print(" Name: {}".format(result["hotelName"])) - # [END get_document_async] - - -if __name__ == "__main__": - asyncio.run(autocomplete_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py deleted file mode 100644 index 3a47a8fb8641..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_index_alias_crud_operations_async.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete an alias with an existing index. -USAGE: - python sample_index_alias_crud_operations_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key - 3) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") -""" - - -import asyncio -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] -alias_name = "motels" - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.aio import SearchIndexClient -from azure.search.documents.indexes.models import ( - ComplexField, - CorsOptions, - ScoringProfile, - SearchAlias, - SearchIndex, - SimpleField, - SearchableField, - SearchFieldDataType, -) - - -client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - - -async def create_alias(): - # [START create_alias_async] - alias = SearchAlias(name=alias_name, indexes=[index_name]) - result = await client.create_alias(alias) - # [END create_alias_async] - - -async def get_alias(): - # [START get_alias_async] - result = await client.get_alias(alias_name) - # [END get_alias_async] - - -async def update_alias(): - # [START update_alias_async] - new_index_name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - SearchableField(name="hotelName", type=SearchFieldDataType.String), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex( - name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options - ) - - result_index = await client.create_or_update_index(index=index) - - alias = SearchAlias(name=alias_name, indexes=[new_index_name]) - result = await client.create_or_update_alias(alias) - - # [END update_alias_async] - - -async def delete_alias(): - # [START delete_alias_async] - - await client.delete_alias(alias_name) - # [END delete_alias_async] - - -async def main(): - await create_alias() - await get_alias() - await update_alias() - await delete_alias() - await client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py deleted file mode 100644 index cd767d24f621..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_index_client_send_request_async.py - -DESCRIPTION: - This sample demonstrates how to make custom HTTP requests through a client pipeline. - -USAGE: - python sample_index_client_send_request_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import asyncio -import os -from azure.core.credentials import AzureKeyCredential -from azure.core.rest import HttpRequest -from azure.search.documents.indexes.aio import SearchIndexClient - - -async def sample_send_request(): - endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - client = SearchIndexClient(endpoint, AzureKeyCredential(key)) - - # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, - # while adding convenience for endpoint construction. - request = HttpRequest(method="GET", url=f"/indexes('{index_name}')?api-version=2024-05-01-preview") - async with client: - response = await client.send_request(request) - response.raise_for_status() - response_body = response.json() - print(response_body) - - -if __name__ == "__main__": - asyncio.run(sample_send_request()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py deleted file mode 100644 index 8431867adfb0..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py +++ /dev/null @@ -1,127 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_index_crud_operations_async.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete an index. -USAGE: - python sample_index_crud_operations_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - - -import os -import asyncio -from typing import List - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.aio import SearchIndexClient -from azure.search.documents.indexes.models import ( - ComplexField, - CorsOptions, - SearchIndex, - ScoringProfile, - SearchFieldDataType, - SimpleField, - SearchableField, -) - - -async def create_index(): - # [START create_index_async] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profiles: List[ScoringProfile] = [] - index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) - - result = await client.create_index(index) - await client.close() - # [END create_index_async] - - -async def get_index(): - # [START get_index_async] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - result = await client.get_index(name) - await client.close() - # [END get_index_async] - - -async def update_index(): - # [START update_index_async] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) - - result = await client.create_or_update_index(index=index) - await client.close() - # [END update_index_async] - - -async def delete_index(): - # [START delete_index_async] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - await client.delete_index(name) - await client.close() - # [END delete_index_async] - - -async def main(): - await create_index() - await get_index() - await update_index() - await delete_index() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py deleted file mode 100644 index e83e1bbc66c3..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_indexer_operations_async.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete a Indexer. -USAGE: - python sample_indexer_operations_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - -import asyncio -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] -connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.models import ( - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, - SearchIndex, - SearchIndexer, - SimpleField, - SearchFieldDataType, -) -from azure.search.documents.indexes.aio import SearchIndexerClient, SearchIndexClient - -indexers_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - - -async def create_indexer(): - # create an index - index_name = "async-indexer-hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - index = SearchIndex(name=index_name, fields=fields) - ind_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - async with ind_client: - await ind_client.create_index(index) - - # [START create_indexer_async] - # create a datasource - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name="async-indexer-datasource", type="azureblob", connection_string=connection_string, container=container - ) - data_source = await indexers_client.create_data_source_connection(data_source_connection) - - # create an indexer - indexer = SearchIndexer( - name="async-sample-indexer", - data_source_name="async-indexer-datasource", - target_index_name="async-indexer-hotels", - ) - result = await indexers_client.create_indexer(indexer) - print("Create new Indexer - async-sample-indexer") - # [END create_indexer_async] - - -async def list_indexers(): - # [START list_indexer_async] - result = await indexers_client.get_indexers() - names = [x.name for x in result] - print("Found {} Indexers in the service: {}".format(len(result), ", ".join(names))) - # [END list_indexer_async] - - -async def get_indexer(): - # [START get_indexer_async] - result = await indexers_client.get_indexer("async-sample-indexer") - print("Retrived Indexer 'async-sample-indexer'") - return result - # [END get_indexer_async] - - -async def get_indexer_status(): - # [START get_indexer_status_async] - result = await indexers_client.get_indexer_status("async-sample-indexer") - print("Retrived Indexer status for 'async-sample-indexer'") - return result - # [END get_indexer_status_async] - - -async def run_indexer(): - # [START run_indexer_async] - await indexers_client.run_indexer("async-sample-indexer") - print("Ran the Indexer 'async-sample-indexer'") - return - # [END run_indexer_async] - - -async def reset_indexer(): - # [START reset_indexer_async] - await indexers_client.reset_indexer("async-sample-indexer") - print("Reset the Indexer 'async-sample-indexer'") - return - # [END reset_indexer_async] - - -async def delete_indexer(): - # [START delete_indexer_async] - await indexers_client.delete_indexer("async-sample-indexer") - print("Indexer 'async-sample-indexer' successfully deleted") - # [END delete_indexer_async] - - -async def main(): - await create_indexer() - await list_indexers() - await get_indexer() - await get_indexer_status() - await run_indexer() - await reset_indexer() - await delete_indexer() - await indexers_client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py deleted file mode 100644 index bfd02c0b6e27..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_query_session_async.py -DESCRIPTION: - To ensure more consistent and unique search results within a user's session, you can use session id. - Simply include the session_id parameter in your queries to create a unique identifier for each user session. - This ensures a uniform experience for users throughout their "query session". -USAGE: - python sample_query_session_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def query_session(): - # [START query_session_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - results = await search_client.search(search_text="spa", session_id="session-1") - - print("Hotels containing 'spa' in the name (or other fields):") - async for result in results: - print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) - # [END query_session_async] - - -if __name__ == "__main__": - asyncio.run(query_session()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py deleted file mode 100644 index 3a9c0c13d185..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_search_client_send_request_async.py - -DESCRIPTION: - This sample demonstrates how to make custom HTTP requests through a client pipeline. - -USAGE: - python sample_search_client_send_request_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import asyncio -import os -from azure.core.credentials import AzureKeyCredential -from azure.core.rest import HttpRequest -from azure.search.documents.aio import SearchClient - - -async def sample_send_request(): - endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - client = SearchClient(endpoint, index_name, AzureKeyCredential(key)) - - # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, - # while adding convenience for endpoint construction. - request = HttpRequest(method="GET", url=f"/docs/$count?api-version=2024-05-01-preview") - async with client: - response = await client.send_request(request) - response.raise_for_status() - response_body = response.json() - print(response_body) - - -if __name__ == "__main__": - asyncio.run(sample_send_request()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py deleted file mode 100644 index 42a0cb2874ee..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_semantic_search_async.py -DESCRIPTION: - This sample demonstrates how to use semantic search. -USAGE: - python sample_semantic_search_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - - -async def speller(): - # [START speller_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - credential = AzureKeyCredential(key) - client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) - results = await client.search(search_text="luxury", query_language="en-us", query_speller="lexicon") - - async for result in results: - print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) - # [END speller_async] - - -async def semantic_ranking(): - # [START semantic_ranking_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - credential = AzureKeyCredential(key) - client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) - results = list( - client.search( - search_text="luxury", - query_type="semantic", - semantic_configuration_name="semantic_config_name", - query_language="en-us", - ) - ) - - for result in results: - print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) - # [END semantic_ranking_async] - - -if __name__ == "__main__": - asyncio.run(speller()) - asyncio.run(semantic_ranking()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py deleted file mode 100644 index d5f62acb4ff6..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_simple_query_async.py -DESCRIPTION: - This sample demonstrates how to get search results from a basic search text - from an Azure Search index. -USAGE: - python sample_simple_query_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def simple_text_query(): - # [START simple_query_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - results = await search_client.search(search_text="spa") - - print("Hotels containing 'spa' in the name (or other fields):") - async for result in results: - print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) - # [END simple_query_async] - - -if __name__ == "__main__": - asyncio.run(simple_text_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py deleted file mode 100644 index 8f3fef5a90af..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_suggestions_async.py -DESCRIPTION: - This sample demonstrates how to obtain search suggestions from an Azure - search index. -USAGE: - python sample_suggestions_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -async def suggest_query(): - # [START suggest_query_async] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.aio import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - async with search_client: - results = await search_client.suggest(search_text="coffee", suggester_name="sg") - - print("Search suggestions for 'coffee'") - for result in results: - hotel = await search_client.get_document(key=result["hotelId"]) - print(" Text: {} for Hotel: {}".format(repr(result["text"]), hotel["hotelName"])) - # [END suggest_query_async] - - -if __name__ == "__main__": - asyncio.run(suggest_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py deleted file mode 100644 index d45d375563d9..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_synonym_map_operations_async.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete a Synonym Map. -USAGE: - python sample_synonym_map_operations_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - -import asyncio -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.aio import SearchIndexClient -from azure.search.documents.indexes.models import SynonymMap - -client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - - -async def create_synonym_map(): - # [START create_synonym_map_async] - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name="test-syn-map", synonyms=synonyms) - result = await client.create_synonym_map(synonym_map) - print("Create new Synonym Map 'test-syn-map succeeded") - # [END create_synonym_map_async] - - -async def get_synonym_maps(): - # [START get_synonym_maps_async] - result = await client.get_synonym_maps() - names = [x.name for x in result] - print("Found {} Synonym Maps in the service: {}".format(len(result), ", ".join(names))) - # [END get_synonym_maps_async] - - -async def get_synonym_map(): - # [START get_synonym_map_async] - result = await client.get_synonym_map("test-syn-map") - print("Retrived Synonym Map 'test-syn-map' with synonyms") - if result: - for syn in result.synonyms: - print(" {}".format(syn)) - # [END get_synonym_map_async] - - -async def delete_synonym_map(): - # [START delete_synonym_map_async] - await client.delete_synonym_map("test-syn-map") - print("Synonym Map 'test-syn-map' deleted") - # [END delete_synonym_map_async] - - -async def main(): - await create_synonym_map() - await get_synonym_maps() - await get_synonym_map() - await delete_synonym_map() - await client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py deleted file mode 100644 index 269226f313d6..000000000000 --- a/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_vector_search_async.py -DESCRIPTION: - This sample demonstrates how to get search results from a basic search text - from an Azure Search index. -USAGE: - python sample_vector_search_async.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -import asyncio - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.aio import SearchClient -from azure.search.documents.indexes import SearchIndexClient -from azure.search.documents.models import VectorizedQuery - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def get_embeddings(text: str): - # There are a few ways to get embeddings. This is just one example. - import openai - - open_ai_endpoint = os.getenv("OpenAIEndpoint") - open_ai_key = os.getenv("OpenAIKey") - - client = openai.AzureOpenAI( - azure_endpoint=open_ai_endpoint, - api_key=open_ai_key, - api_version="2023-09-01-preview", - ) - embedding = client.embeddings.create(input=[text], model="text-embedding-ada-002") - return embedding.data[0].embedding - - -def get_hotel_index(name: str): - from azure.search.documents.indexes.models import ( - SearchIndex, - SearchField, - SearchFieldDataType, - SimpleField, - SearchableField, - VectorSearch, - VectorSearchProfile, - HnswAlgorithmConfiguration, - ) - - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SearchableField(name="hotelName", type=SearchFieldDataType.String, sortable=True, filterable=True), - SearchableField(name="description", type=SearchFieldDataType.String), - SearchField( - name="descriptionVector", - type=SearchFieldDataType.Collection(SearchFieldDataType.Single), - searchable=True, - vector_search_dimensions=1536, - vector_search_profile_name="my-vector-config", - ), - SearchableField( - name="category", type=SearchFieldDataType.String, sortable=True, filterable=True, facetable=True - ), - ] - vector_search = VectorSearch( - profiles=[VectorSearchProfile(name="my-vector-config", algorithm_configuration_name="my-algorithms-config")], - algorithms=[HnswAlgorithmConfiguration(name="my-algorithms-config")], - ) - return SearchIndex(name=name, fields=fields, vector_search=vector_search) - - -def get_hotel_documents(): - docs = [ - { - "hotelId": "1", - "hotelName": "Fancy Stay", - "description": "Best hotel in town if you like luxury hotels.", - "descriptionVector": get_embeddings("Best hotel in town if you like luxury hotels."), - "category": "Luxury", - }, - { - "hotelId": "2", - "hotelName": "Roach Motel", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionVector": get_embeddings("Cheapest hotel in town. Infact, a motel."), - "category": "Budget", - }, - { - "hotelId": "3", - "hotelName": "EconoStay", - "description": "Very popular hotel in town.", - "descriptionVector": get_embeddings("Very popular hotel in town."), - "category": "Budget", - }, - { - "hotelId": "4", - "hotelName": "Modern Stay", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionVector": get_embeddings( - "Modern architecture, very polite staff and very clean. Also very affordable." - ), - "category": "Luxury", - }, - { - "hotelId": "5", - "hotelName": "Secret Point", - "description": "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York.", - "descriptionVector": get_embeddings( - "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York." - ), - "category": "Boutique", - }, - ] - return docs - - -async def single_vector_search(): - # [START single_vector_search] - query = "Top hotels in town" - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") - - async with search_client: - results = await search_client.search( - search_text="", - vector_queries=[vector_query], - select=["hotelId", "hotelName"], - ) - - async for result in results: - print(result) - # [END single_vector_search] - - -async def single_vector_search_with_filter(): - # [START single_vector_search_with_filter] - query = "Top hotels in town" - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") - - async with search_client: - results = await search_client.search( - vector_queries=[vector_query], - filter="category eq 'Luxury'", - select=["hotelId", "hotelName"], - ) - - async for result in results: - print(result) - # [END single_vector_search_with_filter] - - -async def simple_hybrid_search(): - # [START simple_hybrid_search] - query = "Top hotels in town" - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") - - async with search_client: - results = await search_client.search( - search_text=query, - vector_queries=[vector_query], - select=["hotelId", "hotelName"], - ) - - async for result in results: - print(result) - # [END simple_hybrid_search] - - -async def main(): - credential = AzureKeyCredential(key) - index_client = SearchIndexClient(service_endpoint, credential) - index = get_hotel_index(index_name) - index_client.create_index(index) - client = SearchClient(service_endpoint, index_name, credential) - hotel_docs = get_hotel_documents() - await client.upload_documents(documents=hotel_docs) - - await single_vector_search() - await single_vector_search_with_filter() - await simple_hybrid_search() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/files/hotel_small.json b/sdk/search/azure-search-documents/samples/files/hotel_small.json deleted file mode 100644 index e30a1f96199b..000000000000 --- a/sdk/search/azure-search-documents/samples/files/hotel_small.json +++ /dev/null @@ -1,252 +0,0 @@ -[ - { - "@search.action": "upload", - "hotelId": "1", - "hotelName": "Fancy Stay", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "2", - "hotelName": "Roach Motel", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "3", - "hotelName": "EconoStay", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "4", - "hotelName": "Express Rooms", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "5", - "hotelName": "Comfy Place", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "6", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "7", - "hotelName": "Modern Stay", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "8", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "9", - "hotelName": "Secret Point Motel", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "10", - "hotelName": "Countryside Hotel", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - } -] diff --git a/sdk/search/azure-search-documents/samples/sample_analyze_text.py b/sdk/search/azure-search-documents/samples/sample_analyze_text.py deleted file mode 100644 index 3a239870ea17..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_analyze_text.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_analyze_text.py -DESCRIPTION: - This sample demonstrates how to analyze text. -USAGE: - python sample_analyze_text.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def simple_analyze_text(): - # [START simple_analyze_text] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.indexes import SearchIndexClient - from azure.search.documents.indexes.models import AnalyzeTextOptions - - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - - analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") - - result = client.analyze_text(index_name, analyze_request) - print(result.as_dict()) - # [END simple_analyze_text] - - -if __name__ == "__main__": - simple_analyze_text() diff --git a/sdk/search/azure-search-documents/samples/sample_authentication.py b/sdk/search/azure-search-documents/samples/sample_authentication.py deleted file mode 100644 index f690c7ff7e17..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_authentication.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_authentication.py -DESCRIPTION: - This sample demonstrates how to authenticate with the Azure Congnitive Search - service with an API key. See more details about authentication here: - https://learn.microsoft.com/azure.search.documents/search-security-api-keys -USAGE: - python sample_authentication.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - - -def authentication_with_api_key_credential(): - # [START create_search_client_with_key] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - # [END create_search_client_with_key] - - result = search_client.get_document_count() - - print("There are {} documents in the {} search index.".format(result, index_name)) - - -def authentication_service_client_with_api_key_credential(): - # [START create_search_service_client_with_key] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents.indexes import SearchIndexClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - search_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - # [END create_search_service_client_with_key] - - -def authentication_with_aad(): - # [START authentication_with_aad] - from azure.identity import DefaultAzureCredential - from azure.search.documents import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - credential = DefaultAzureCredential() - - search_client = SearchClient(service_endpoint, index_name, credential) - # [END authentication_with_aad] - - result = search_client.get_document_count() - - print("There are {} documents in the {} search index.".format(result, index_name)) - - -def authentication_service_client_with_aad(): - # [START authentication_service_client_with_aad] - from azure.identity import DefaultAzureCredential - from azure.search.documents.indexes import SearchIndexClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - credential = DefaultAzureCredential() - - search_client = SearchIndexClient(service_endpoint, credential) - # [END authentication_service_client_with_aad] - - -if __name__ == "__main__": - authentication_with_api_key_credential() - authentication_service_client_with_api_key_credential() - authentication_with_aad() - authentication_service_client_with_aad() diff --git a/sdk/search/azure-search-documents/samples/sample_autocomplete.py b/sdk/search/azure-search-documents/samples/sample_autocomplete.py deleted file mode 100644 index 7846637b5dbc..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_autocomplete.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_autocomplete.py -DESCRIPTION: - This sample demonstrates how to obtain autocompletion suggestions from an - Azure Search index. -USAGE: - python sample_autocomplete.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def autocomplete_query(): - # [START autocomplete_query] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - results = search_client.autocomplete(search_text="bo", suggester_name="sg") - - print("Autocomplete suggestions for 'bo'") - for result in results: - print(" Completion: {}".format(result["text"])) - # [END autocomplete_query] - - -if __name__ == "__main__": - autocomplete_query() diff --git a/sdk/search/azure-search-documents/samples/sample_buffered_sender.py b/sdk/search/azure-search-documents/samples/sample_buffered_sender.py deleted file mode 100644 index db7de92154a2..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_buffered_sender.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_batch_client.py -DESCRIPTION: - This sample demonstrates how to upload, merge, or delete documents using SearchIndexingBufferedSender. -USAGE: - python sample_batch_client.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchIndexingBufferedSender - - -def sample_batching_client(): - DOCUMENT = { - "category": "Hotel", - "hotelId": "1000", - "rating": 4.0, - "rooms": [], - "hotelName": "Azure Inn", - } - - with SearchIndexingBufferedSender(service_endpoint, index_name, AzureKeyCredential(key)) as batch_client: - # add upload actions - batch_client.upload_documents(documents=[DOCUMENT]) - # add merge actions - batch_client.merge_documents(documents=[{"hotelId": "1000", "rating": 4.5}]) - # add delete actions - batch_client.delete_documents(documents=[{"hotelId": "1000"}]) - - -if __name__ == "__main__": - sample_batching_client() diff --git a/sdk/search/azure-search-documents/samples/sample_crud_operations.py b/sdk/search/azure-search-documents/samples/sample_crud_operations.py deleted file mode 100644 index de22c6b5cb82..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_crud_operations.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_crud_operations.py -DESCRIPTION: - This sample demonstrates how to upload, merge, or delete documents from an - Azure Search index. -USAGE: - python sample_crud_operations.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient - -search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - -def upload_document(): - # [START upload_document] - DOCUMENT = { - "hotelId": "1000", - "hotelName": "Azure Inn", - } - - result = search_client.upload_documents(documents=[DOCUMENT]) - - print("Upload of new document succeeded: {}".format(result[0].succeeded)) - # [END upload_document] - - -def merge_document(): - # [START merge_document] - result = search_client.merge_documents(documents=[{"hotelId": "783", "hotelName": "Renovated Ranch"}]) - - print("Merge into new document succeeded: {}".format(result[0].succeeded)) - # [END merge_document] - - -def delete_document(): - # [START delete_document] - result = search_client.delete_documents(documents=[{"hotelId": "1000"}]) - - print("Delete new document succeeded: {}".format(result[0].succeeded)) - # [END delete_document] - - -if __name__ == "__main__": - upload_document() - merge_document() - delete_document() diff --git a/sdk/search/azure-search-documents/samples/sample_data_source_operations.py b/sdk/search/azure-search-documents/samples/sample_data_source_operations.py deleted file mode 100644 index cf14b3fa25cf..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_data_source_operations.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_data_source_operations.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete a Data Source. -USAGE: - python sample_data_source_operations.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] -connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes import SearchIndexerClient -from azure.search.documents.indexes.models import SearchIndexerDataContainer, SearchIndexerDataSourceConnection - -client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - - -def create_data_source_connection(): - # [START create_data_source_connection] - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name="sample-data-source-connection", type="azureblob", connection_string=connection_string, container=container - ) - result = client.create_data_source_connection(data_source_connection) - print(result) - print("Create new Data Source Connection - sample-data-source-connection") - # [END create_data_source_connection] - - -def list_data_source_connections(): - # [START list_data_source_connection] - result = client.get_data_source_connections() - names = [ds.name for ds in result] - print("Found {} Data Source Connections in the service: {}".format(len(result), ", ".join(names))) - # [END list_data_source_connection] - - -def get_data_source_connection(): - # [START get_data_source_connection] - result = client.get_data_source_connection("sample-data-source-connection") - print("Retrived Data Source Connection 'sample-data-source-connection'") - # [END get_data_source_connection] - - -def delete_data_source_connection(): - # [START delete_data_source_connection] - client.delete_data_source_connection("sample-data-source-connection") - print("Data Source Connection 'sample-data-source-connection' successfully deleted") - # [END delete_data_source_connection] - - -if __name__ == "__main__": - create_data_source_connection() - list_data_source_connections() - get_data_source_connection() - delete_data_source_connection() diff --git a/sdk/search/azure-search-documents/samples/sample_facet_query.py b/sdk/search/azure-search-documents/samples/sample_facet_query.py deleted file mode 100644 index a70078173d11..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_facet_query.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_facet_query.py -DESCRIPTION: - This sample demonstrates how to obtain search facets on specified field in - an Azure Search index. -USAGE: - python sample_facet_query.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -from typing import List, Dict, cast -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def filter_query(): - # [START facet_query] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - results = search_client.search(search_text="WiFi", facets=["category,count:3", "parkingIncluded"]) - - facets: Dict[str, List[str]] = cast(Dict[str, List[str]], results.get_facets()) - - print("Catgory facet counts for hotels:") - for facet in facets["category"]: - print(" {}".format(facet)) - # [END facet_query] - - -if __name__ == "__main__": - filter_query() diff --git a/sdk/search/azure-search-documents/samples/sample_filter_query.py b/sdk/search/azure-search-documents/samples/sample_filter_query.py deleted file mode 100644 index 432edf9a1f02..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_filter_query.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_filter_query.py -DESCRIPTION: - This sample demonstrates how search results from an Azure Search index can - be filtered and ordered. -USAGE: - python sample_filter_query.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def filter_query(): - # [START filter_query] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - results = search_client.search( - search_text="WiFi", - filter="Address/StateProvince eq 'FL' and Address/Country eq 'USA'", - select=["hotelName", "rating"], - order_by=["rating desc"], - ) - - print("Florida hotels containing 'WiFi', sorted by Rating:") - for result in results: - print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) - # [END filter_query] - - -if __name__ == "__main__": - filter_query() diff --git a/sdk/search/azure-search-documents/samples/sample_get_document.py b/sdk/search/azure-search-documents/samples/sample_get_document.py deleted file mode 100644 index 0a5addfa14cb..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_get_document.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_get_document.py -DESCRIPTION: - This sample demonstrates how to retrieve a specific document by key from an - Azure Search index. -USAGE: - python sample_get_document.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def get_document(): - # [START get_document] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - result = search_client.get_document(key="23") - - print("Details for hotel '23' are:") - print(" Name: {}".format(result["hotelName"])) - # [END get_document] - - -if __name__ == "__main__": - get_document() diff --git a/sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py b/sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py deleted file mode 100644 index 52220f12b8e4..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_index_alias_crud_operations.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete an alias with an existing index. -USAGE: - python sample_index_alias_crud_operations.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key - 3) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") -""" - - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] -alias_name = "motels" - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes import SearchIndexClient -from azure.search.documents.indexes.models import ( - ComplexField, - CorsOptions, - ScoringProfile, - SearchAlias, - SearchIndex, - SimpleField, - SearchableField, - SearchFieldDataType, -) - - -client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - - -def create_alias(): - # [START create_alias] - alias = SearchAlias(name=alias_name, indexes=[index_name]) - result = client.create_alias(alias) - # [END create_alias] - - -def get_alias(): - # [START get_alias] - result = client.get_alias(alias_name) - # [END get_alias] - - -def update_alias(): - # [START update_alias] - new_index_name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - SearchableField(name="hotelName", type=SearchFieldDataType.String), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex( - name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options - ) - - result_index = client.create_or_update_index(index=index) - - alias = SearchAlias(name=alias_name, indexes=[new_index_name]) - result = client.create_or_update_alias(alias) - - # [END update_alias] - - -def delete_alias(): - # [START delete_alias] - - client.delete_alias(alias_name) - # [END delete_alias] - - -if __name__ == "__main__": - create_alias() - get_alias() - update_alias() - delete_alias() diff --git a/sdk/search/azure-search-documents/samples/sample_index_client_send_request.py b/sdk/search/azure-search-documents/samples/sample_index_client_send_request.py deleted file mode 100644 index f8b373b1970b..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_index_client_send_request.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_index_client_send_request.py - -DESCRIPTION: - This sample demonstrates how to make custom HTTP requests through a client pipeline. - -USAGE: - python sample_index_client_send_request.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -from azure.core.credentials import AzureKeyCredential -from azure.core.rest import HttpRequest -from azure.search.documents.indexes import SearchIndexClient - - -def sample_send_request(): - endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - client = SearchIndexClient(endpoint, AzureKeyCredential(key)) - - # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, - # while adding convenience for endpoint construction. - request = HttpRequest(method="GET", url=f"/indexes('{index_name}')?api-version=2024-05-01-preview") - response = client.send_request(request) - response.raise_for_status() - response_body = response.json() - print(response_body) - - -if __name__ == "__main__": - sample_send_request() diff --git a/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py b/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py deleted file mode 100644 index 6b0cabb2c2dd..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_index_crud_operations.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete an index. -USAGE: - python sample_index_crud_operations.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - - -import os -from typing import List - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes import SearchIndexClient -from azure.search.documents.indexes.models import ( - ComplexField, - CorsOptions, - SearchIndex, - ScoringProfile, - SearchFieldDataType, - SimpleField, - SearchableField, -) - - -def create_index(): - # [START create_index] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profiles: List[ScoringProfile] = [] - index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) - - result = client.create_index(index) - # [END create_index] - - -def get_index(): - # [START get_index] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - result = client.get_index(name) - # [END get_index] - - -def update_index(): - # [START update_index] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) - - result = client.create_or_update_index(index=index) - # [END update_index] - - -def delete_index(): - # [START delete_index] - client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - name = "hotels" - client.delete_index(name) - # [END delete_index] - - -if __name__ == "__main__": - create_index() - get_index() - update_index() - delete_index() diff --git a/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py b/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py deleted file mode 100644 index b0654e56210f..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py +++ /dev/null @@ -1,152 +0,0 @@ -""" -FILE: sample_indexer_datasource_skillset.py -DESCRIPTION: - This sample demonstrates use an indexer, datasource and skillset together. - - Indexer is used to efficiently write data to an index using a datasource. - So we first identify a supported data source - we use azure storage blobs - in this example. Then we create an index which is compatible with the datasource. - Further, we create an azure cognitive search datasource which we require to finally - create an indexer. - - Additionally, we will also use skillsets to provide some AI enhancements in our indexers. - - Once we create the indexer, we run the indexer and perform some basic operations like getting - the indexer status. - - The datasource used in this sample is stored as metadata for empty blobs in "searchcontainer". - The json file can be found in samples/files folder named hotel_small.json has the metdata of - each blob. -USAGE: - python sample_indexer_datasource_skillset.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key - 3) AZURE_STORAGE_CONNECTION_STRING - The connection string for the storage blob account that is - being used to create the datasource. -""" - -import os -import datetime - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] -connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.models import ( - SearchIndexerDataContainer, - SearchIndex, - SearchIndexer, - SimpleField, - SearchFieldDataType, - EntityRecognitionSkill, - InputFieldMappingEntry, - OutputFieldMappingEntry, - SearchIndexerSkillset, - CorsOptions, - IndexingSchedule, - SearchableField, - IndexingParameters, - SearchIndexerDataSourceConnection, - IndexingParametersConfiguration, -) -from azure.search.documents.indexes import SearchIndexerClient, SearchIndexClient - - -def _create_index(): - name = "hotel-index" - - # Here we create an index with listed fields. - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, filterable=True, sortable=True, key=True), - SearchableField(name="hotelName", type=SearchFieldDataType.String), - SimpleField(name="description", type=SearchFieldDataType.String), - SimpleField(name="descriptionFr", type=SearchFieldDataType.String), - SimpleField(name="category", type=SearchFieldDataType.String), - SimpleField(name="parkingIncluded", type=SearchFieldDataType.Boolean, filterable=True), - SimpleField(name="smokingAllowed", type=SearchFieldDataType.Boolean, filterable=True), - SimpleField(name="lastRenovationDate", type=SearchFieldDataType.String), - SimpleField(name="rating", type=SearchFieldDataType.Int64, sortable=True), - SimpleField(name="location", type=SearchFieldDataType.GeographyPoint), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - - # pass in the name, fields and cors options and create the index - index = SearchIndex(name=name, fields=fields, cors_options=cors_options) - index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - result = index_client.create_index(index) - return result - - -def _create_datasource(): - # Here we create a datasource. As mentioned in the description we have stored it in - # "searchcontainer" - ds_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name="hotel-datasource", type="azureblob", connection_string=connection_string, container=container - ) - data_source = ds_client.create_data_source_connection(data_source_connection) - return data_source - - -def _create_skillset(): - client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - inp = InputFieldMappingEntry(name="text", source="/document/lastRenovationDate") - output = OutputFieldMappingEntry(name="dateTimes", target_name="RenovatedDate") - s = EntityRecognitionSkill(name="merge-skill", inputs=[inp], outputs=[output]) - - skillset = SearchIndexerSkillset(name="hotel-data-skill", skills=[s], description="example skillset") - result = client.create_skillset(skillset) - return result - - -def sample_indexer_workflow(): - # Now that we have a datasource and an index, we can create an indexer. - - skillset_name = _create_skillset().name - print("Skillset is created") - - ds_name = _create_datasource().name - print("Data source is created") - - ind_name = _create_index().name - print("Index is created") - - # we pass the data source, skillsets and targeted index to build an indexer - configuration = IndexingParametersConfiguration(parsing_mode="jsonArray", query_timeout=None) # type: ignore - parameters = IndexingParameters(configuration=configuration) - indexer = SearchIndexer( - name="hotel-data-indexer", - data_source_name=ds_name, - target_index_name=ind_name, - skillset_name=skillset_name, - parameters=parameters, - ) - - indexer_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - indexer_client.create_indexer(indexer) # create the indexer - - # to get an indexer - result = indexer_client.get_indexer("hotel-data-indexer") - print(result) - - # To run an indexer, we can use run_indexer() - indexer_client.run_indexer(result.name) - - # Using create or update to schedule an indexer - - schedule = IndexingSchedule(interval=datetime.timedelta(hours=24)) - result.schedule = schedule - updated_indexer = indexer_client.create_or_update_indexer(result) - - print(updated_indexer) - - # get the status of an indexer - indexer_client.get_indexer_status(updated_indexer.name) - - -if __name__ == "__main__": - sample_indexer_workflow() diff --git a/sdk/search/azure-search-documents/samples/sample_indexers_operations.py b/sdk/search/azure-search-documents/samples/sample_indexers_operations.py deleted file mode 100644 index ff854d51be96..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_indexers_operations.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_indexer_operations.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete a Indexer. -USAGE: - python sample_indexer_operations.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] -connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes.models import ( - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, - SearchIndex, - SearchIndexer, - SimpleField, - SearchFieldDataType, -) -from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient - -indexers_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) - - -def create_indexer(): - # create an index - index_name = "indexer-hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - index = SearchIndex(name=index_name, fields=fields) - ind_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - ind_client.create_index(index) - - # [START create_indexer] - # create a datasource - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name="indexer-datasource", type="azureblob", connection_string=connection_string, container=container - ) - data_source = indexers_client.create_data_source_connection(data_source_connection) - - # create an indexer - indexer = SearchIndexer( - name="sample-indexer", data_source_name="indexer-datasource", target_index_name="indexer-hotels" - ) - result = indexers_client.create_indexer(indexer) - print("Create new Indexer - sample-indexer") - # [END create_indexer] - - -def list_indexers(): - # [START list_indexer] - result = indexers_client.get_indexers() - names = [x.name for x in result] - print("Found {} Indexers in the service: {}".format(len(result), ", ".join(names))) - # [END list_indexer] - - -def get_indexer(): - # [START get_indexer] - result = indexers_client.get_indexer("sample-indexer") - print("Retrived Indexer 'sample-indexer'") - return result - # [END get_indexer] - - -def get_indexer_status(): - # [START get_indexer_status] - result = indexers_client.get_indexer_status("sample-indexer") - print("Retrived Indexer status for 'sample-indexer'") - return result - # [END get_indexer_status] - - -def run_indexer(): - # [START run_indexer] - result = indexers_client.run_indexer("sample-indexer") - print("Ran the Indexer 'sample-indexer'") - return result - # [END run_indexer] - - -def reset_indexer(): - # [START reset_indexer] - result = indexers_client.reset_indexer("sample-indexer") - print("Reset the Indexer 'sample-indexer'") - return result - # [END reset_indexer] - - -def delete_indexer(): - # [START delete_indexer] - indexers_client.delete_indexer("sample-indexer") - print("Indexer 'sample-indexer' successfully deleted") - # [END delete_indexer] - - -if __name__ == "__main__": - create_indexer() - list_indexers() - get_indexer() - get_indexer_status() - run_indexer() - reset_indexer() - delete_indexer() diff --git a/sdk/search/azure-search-documents/samples/sample_query_session.py b/sdk/search/azure-search-documents/samples/sample_query_session.py deleted file mode 100644 index 64e783ff636a..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_query_session.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_query_session.py -DESCRIPTION: - To ensure more consistent and unique search results within a user's session, you can use session id. - Simply include the session_id parameter in your queries to create a unique identifier for each user session. - This ensures a uniform experience for users throughout their "query session". -USAGE: - python sample_query_session.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def query_session(): - # [START query_session] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - results = search_client.search(search_text="spa", session_id="session-1") - - print("Hotels containing 'spa' in the name (or other fields):") - for result in results: - print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) - # [END query_session] - - -if __name__ == "__main__": - query_session() diff --git a/sdk/search/azure-search-documents/samples/sample_search_client_send_request.py b/sdk/search/azure-search-documents/samples/sample_search_client_send_request.py deleted file mode 100644 index 616d04fe0e52..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_search_client_send_request.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_search_client_send_request.py - -DESCRIPTION: - This sample demonstrates how to make custom HTTP requests through a client pipeline. - -USAGE: - python sample_search_client_send_request.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os -from azure.core.credentials import AzureKeyCredential -from azure.core.rest import HttpRequest -from azure.search.documents import SearchClient - - -def sample_send_request(): - endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - client = SearchClient(endpoint, index_name, AzureKeyCredential(key)) - - # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, - # while adding convenience for endpoint construction. - request = HttpRequest(method="GET", url=f"/docs/$count?api-version=2024-05-01-preview") - response = client.send_request(request) - response.raise_for_status() - response_body = response.json() - print(response_body) - - -if __name__ == "__main__": - sample_send_request() diff --git a/sdk/search/azure-search-documents/samples/sample_semantic_search.py b/sdk/search/azure-search-documents/samples/sample_semantic_search.py deleted file mode 100644 index c6e5be9c57ad..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_semantic_search.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_semantic_search.py -DESCRIPTION: - This sample demonstrates how to use semantic search. -USAGE: - python sample_semantic_search.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - - -def speller(): - # [START speller] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - credential = AzureKeyCredential(key) - client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) - results = list(client.search(search_text="luxury", query_language="en-us", query_speller="lexicon")) - - for result in results: - print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) - # [END speller] - - -def semantic_ranking(): - # [START semantic_ranking] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] - index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] - key = os.environ["AZURE_SEARCH_API_KEY"] - - credential = AzureKeyCredential(key) - client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) - results = list( - client.search( - search_text="luxury", - query_type="semantic", - semantic_configuration_name="semantic_config_name", - query_language="en-us", - ) - ) - - for result in results: - print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) - # [END semantic_ranking] - - -if __name__ == "__main__": - speller() - semantic_ranking() diff --git a/sdk/search/azure-search-documents/samples/sample_simple_query.py b/sdk/search/azure-search-documents/samples/sample_simple_query.py deleted file mode 100644 index 9f2317a008e3..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_simple_query.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_simple_query.py -DESCRIPTION: - This sample demonstrates how to get search results from a basic search text - from an Azure Search index. -USAGE: - python sample_simple_query.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def simple_text_query(): - # [START simple_query] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - results = search_client.search(search_text="spa") - - print("Hotels containing 'spa' in the name (or other fields):") - for result in results: - print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) - # [END simple_query] - - -if __name__ == "__main__": - simple_text_query() diff --git a/sdk/search/azure-search-documents/samples/sample_suggestions.py b/sdk/search/azure-search-documents/samples/sample_suggestions.py deleted file mode 100644 index e24478418b25..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_suggestions.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_suggestions.py -DESCRIPTION: - This sample demonstrates how to obtain search suggestions from an Azure - search index -USAGE: - python sample_suggestions.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def suggest_query(): - # [START suggest_query] - from azure.core.credentials import AzureKeyCredential - from azure.search.documents import SearchClient - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - - results = search_client.suggest(search_text="coffee", suggester_name="sg") - - print("Search suggestions for 'coffee'") - for result in results: - hotel = search_client.get_document(key=result["hotelId"]) - print(" Text: {} for Hotel: {}".format(repr(result["text"]), hotel["hotelName"])) - # [END suggest_query] - - -if __name__ == "__main__": - suggest_query() diff --git a/sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py b/sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py deleted file mode 100644 index c6f8b9575f40..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_synonym_map_operations.py -DESCRIPTION: - This sample demonstrates how to get, create, update, or delete a Synonym Map. -USAGE: - python sample_synonym_map_operations.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -key = os.environ["AZURE_SEARCH_API_KEY"] - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.indexes import SearchIndexClient -from azure.search.documents.indexes.models import SynonymMap - -client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) - - -def create_synonym_map(): - # [START create_synonym_map] - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name="test-syn-map", synonyms=synonyms) - result = client.create_synonym_map(synonym_map) - print("Create new Synonym Map 'test-syn-map succeeded") - # [END create_synonym_map] - - -def create_synonym_map_from_file(): - # [START create_synonym_map_from_file] - from os.path import dirname, join, realpath - - CWD = dirname(realpath(__file__)) - file_path = join(CWD, "synonym_map.txt") - with open(file_path, "r") as f: - solr_format_synonyms = f.read() - synonyms = solr_format_synonyms.split("\n") - synonym_map = SynonymMap(name="test-syn-map", synonyms=synonyms) - result = client.create_synonym_map(synonym_map) - print("Create new Synonym Map 'test-syn-map succeeded") - # [END create_synonym_map_from_file] - - -def get_synonym_maps(): - # [START get_synonym_maps] - result = client.get_synonym_maps() - names = [x.name for x in result] - print("Found {} Synonym Maps in the service: {}".format(len(result), ", ".join(names))) - # [END get_synonym_maps] - - -def get_synonym_map(): - # [START get_synonym_map] - result = client.get_synonym_map("test-syn-map") - print("Retrived Synonym Map 'test-syn-map' with synonyms") - if result: - for syn in result.synonyms: - print(" {}".format(syn)) - # [END get_synonym_map] - - -def delete_synonym_map(): - # [START delete_synonym_map] - client.delete_synonym_map("test-syn-map") - print("Synonym Map 'test-syn-map' deleted") - # [END delete_synonym_map] - - -if __name__ == "__main__": - create_synonym_map() - get_synonym_maps() - get_synonym_map() - delete_synonym_map() diff --git a/sdk/search/azure-search-documents/samples/sample_vector_search.py b/sdk/search/azure-search-documents/samples/sample_vector_search.py deleted file mode 100644 index b7bfbc31d44a..000000000000 --- a/sdk/search/azure-search-documents/samples/sample_vector_search.py +++ /dev/null @@ -1,204 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_vector_search.py -DESCRIPTION: - This sample demonstrates how to get search results from a basic search text - from an Azure Search index. -USAGE: - python sample_vector_search.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient -from azure.search.documents.indexes import SearchIndexClient -from azure.search.documents.models import VectorizedQuery - -service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] -index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] -key = os.environ["AZURE_SEARCH_API_KEY"] - - -def get_embeddings(text: str): - # There are a few ways to get embeddings. This is just one example. - import openai - - open_ai_endpoint = os.getenv("OpenAIEndpoint") - open_ai_key = os.getenv("OpenAIKey") - - client = openai.AzureOpenAI( - azure_endpoint=open_ai_endpoint, - api_key=open_ai_key, - api_version="2023-09-01-preview", - ) - embedding = client.embeddings.create(input=[text], model="text-embedding-ada-002") - return embedding.data[0].embedding - - -def get_hotel_index(name: str): - from azure.search.documents.indexes.models import ( - SearchIndex, - SearchField, - SearchFieldDataType, - SimpleField, - SearchableField, - VectorSearch, - VectorSearchProfile, - HnswAlgorithmConfiguration, - ) - - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SearchableField( - name="hotelName", - type=SearchFieldDataType.String, - sortable=True, - filterable=True, - ), - SearchableField(name="description", type=SearchFieldDataType.String), - SearchField( - name="descriptionVector", - type=SearchFieldDataType.Collection(SearchFieldDataType.Single), - searchable=True, - vector_search_dimensions=1536, - vector_search_profile_name="my-vector-config", - ), - SearchableField( - name="category", - type=SearchFieldDataType.String, - sortable=True, - filterable=True, - facetable=True, - ), - ] - vector_search = VectorSearch( - profiles=[VectorSearchProfile(name="my-vector-config", algorithm_configuration_name="my-algorithms-config")], - algorithms=[HnswAlgorithmConfiguration(name="my-algorithms-config")], - ) - return SearchIndex(name=name, fields=fields, vector_search=vector_search) - - -def get_hotel_documents(): - docs = [ - { - "hotelId": "1", - "hotelName": "Fancy Stay", - "description": "Best hotel in town if you like luxury hotels.", - "descriptionVector": get_embeddings("Best hotel in town if you like luxury hotels."), - "category": "Luxury", - }, - { - "hotelId": "2", - "hotelName": "Roach Motel", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionVector": get_embeddings("Cheapest hotel in town. Infact, a motel."), - "category": "Budget", - }, - { - "hotelId": "3", - "hotelName": "EconoStay", - "description": "Very popular hotel in town.", - "descriptionVector": get_embeddings("Very popular hotel in town."), - "category": "Budget", - }, - { - "hotelId": "4", - "hotelName": "Modern Stay", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionVector": get_embeddings( - "Modern architecture, very polite staff and very clean. Also very affordable." - ), - "category": "Luxury", - }, - { - "hotelId": "5", - "hotelName": "Secret Point", - "description": "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York.", - "descriptionVector": get_embeddings( - "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York." - ), - "category": "Boutique", - }, - ] - return docs - - -def single_vector_search(): - # [START single_vector_search] - query = "Top hotels in town" - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") - - results = search_client.search( - vector_queries=[vector_query], - select=["hotelId", "hotelName"], - ) - - for result in results: - print(result) - # [END single_vector_search] - - -def single_vector_search_with_filter(): - # [START single_vector_search_with_filter] - query = "Top hotels in town" - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") - - results = search_client.search( - search_text="", - vector_queries=[vector_query], - filter="category eq 'Luxury'", - select=["hotelId", "hotelName"], - ) - - for result in results: - print(result) - # [END single_vector_search_with_filter] - - -def simple_hybrid_search(): - # [START simple_hybrid_search] - query = "Top hotels in town" - - search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) - vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") - - results = search_client.search( - search_text=query, - vector_queries=[vector_query], - select=["hotelId", "hotelName"], - ) - - for result in results: - print(result) - # [END simple_hybrid_search] - - -if __name__ == "__main__": - credential = AzureKeyCredential(key) - index_client = SearchIndexClient(service_endpoint, credential) - index = get_hotel_index(index_name) - index_client.create_index(index) - client = SearchClient(service_endpoint, index_name, credential) - hotel_docs = get_hotel_documents() - client.upload_documents(documents=hotel_docs) - - single_vector_search() - single_vector_search_with_filter() - simple_hybrid_search() diff --git a/sdk/search/azure-search-documents/samples/synonym_map.txt b/sdk/search/azure-search-documents/samples/synonym_map.txt deleted file mode 100644 index 96f535332c9a..000000000000 --- a/sdk/search/azure-search-documents/samples/synonym_map.txt +++ /dev/null @@ -1,2 +0,0 @@ -USA, United States, United States of America -Washington, Wash. => WA \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py deleted file mode 100644 index 3c166e74983c..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py +++ /dev/null @@ -1,159 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -from unittest import mock -import pytest -from azure.search.documents.aio import ( - SearchIndexingBufferedSender, -) -from azure.core.credentials import AzureKeyCredential -from azure.core.exceptions import HttpResponseError, ServiceResponseTimeoutError -from azure.search.documents.models import IndexingResult -from test_search_index_client_async import await_prepared_test - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - - -class TestSearchBatchingClientAsync: - @await_prepared_test - async def test_search_indexing_buffered_sender_kwargs(self): - async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, window=100) as client: - assert client._batch_action_count == 512 - assert client._max_retries_per_action == 3 - assert client._auto_flush_interval == 60 - assert client._auto_flush - - @await_prepared_test - async def test_batch_queue(self): - async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: - assert client._index_documents_batch - await client.upload_documents(["upload1"]) - await client.delete_documents(["delete1", "delete2"]) - await client.merge_documents(["merge1", "merge2", "merge3"]) - await client.merge_or_upload_documents(["merge_or_upload1"]) - assert len(client.actions) == 7 - actions = await client._index_documents_batch.dequeue_actions() - assert len(client.actions) == 0 - await client._index_documents_batch.enqueue_actions(actions) - assert len(client.actions) == 7 - - @await_prepared_test - @mock.patch( - "azure.search.documents.aio._search_indexing_buffered_sender_async.SearchIndexingBufferedSender._process_if_needed" - ) - async def test_process_if_needed(self, mock_process_if_needed): - async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL) as client: - await client.upload_documents(["upload1"]) - await client.delete_documents(["delete1", "delete2"]) - assert mock_process_if_needed.called - - @await_prepared_test - @mock.patch( - "azure.search.documents.aio._search_indexing_buffered_sender_async.SearchIndexingBufferedSender._cleanup" - ) - async def test_context_manager(self, mock_cleanup): - async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: - await client.upload_documents(["upload1"]) - await client.delete_documents(["delete1", "delete2"]) - assert mock_cleanup.called - - @await_prepared_test - async def test_flush(self): - DOCUMENT = { - "category": "Hotel", - "hotelId": "1000", - "rating": 4.0, - "rooms": [], - "hotelName": "Azure Inn", - } - with mock.patch.object( - SearchIndexingBufferedSender, - "_index_documents_actions", - side_effect=HttpResponseError("Error"), - ): - async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: - client._index_key = "hotelId" - await client.upload_documents([DOCUMENT]) - await client.flush() - assert len(client.actions) == 0 - - @await_prepared_test - async def test_callback_new(self): - on_new = mock.AsyncMock() - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False, on_new=on_new - ) as client: - await client.upload_documents(["upload1"]) - assert on_new.called - - @await_prepared_test - async def test_callback_error(self): - async def mock_fail_index_documents(actions, timeout=86400): - if len(actions) > 0: - result = IndexingResult() - result.key = actions[0].additional_properties.get("id") - result.status_code = 400 - result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 - return [result] - - on_error = mock.AsyncMock() - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error - ) as client: - client._index_documents_actions = mock_fail_index_documents - client._index_key = "id" - await client.upload_documents({"id": 0}) - await client.flush() - assert on_error.called - - @await_prepared_test - async def test_callback_error_on_timeout(self): - async def mock_fail_index_documents(actions, timeout=86400): - if len(actions) > 0: - result = IndexingResult() - result.key = actions[0].additional_properties.get("id") - result.status_code = 400 - result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 - time.sleep(1) - return [result] - - on_error = mock.AsyncMock() - async with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error - ) as client: - client._index_documents_actions = mock_fail_index_documents - client._index_key = "id" - await client.upload_documents([{"id": 0}, {"id": 1}]) - with pytest.raises(ServiceResponseTimeoutError): - await client.flush(timeout=-1) - assert on_error.call_count == 2 - - @await_prepared_test - async def test_callback_progress(self): - async def mock_successful_index_documents(actions, timeout=86400): - if len(actions) > 0: - result = IndexingResult() - result.key = actions[0].additional_properties.get("id") - result.status_code = 200 - result.succeeded = True - return [result] - - on_progress = mock.AsyncMock() - on_remove = mock.AsyncMock() - async with SearchIndexingBufferedSender( - "endpoint", - "index name", - CREDENTIAL, - auto_flush=False, - on_progress=on_progress, - on_remove=on_remove, - ) as client: - client._index_documents_actions = mock_successful_index_documents - client._index_key = "id" - await client.upload_documents({"id": 0}) - await client.flush() - assert on_progress.called - assert on_remove.called diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py deleted file mode 100644 index c41691889a96..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -from unittest import mock -from azure.core.credentials import AzureKeyCredential -from azure.search.documents._generated.models import SearchDocumentsResult, SearchResult -from azure.search.documents.aio import SearchClient -from azure.search.documents.aio._search_client_async import AsyncSearchPageIterator -from test_search_index_client_async import await_prepared_test - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - - -class TestSearchClientAsync: - @await_prepared_test - @mock.patch( - "azure.search.documents._generated.aio.operations._documents_operations.DocumentsOperations.search_post" - ) - async def test_get_count_reset_continuation_token(self, mock_search_post): - client = SearchClient("endpoint", "index name", CREDENTIAL) - result = await client.search(search_text="search text") - assert result._page_iterator_class is AsyncSearchPageIterator - search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] - mock_search_post.return_value = search_result - await result.__anext__() - result._first_page_iterator_instance.continuation_token = "fake token" - await result.get_count() - assert not result._first_page_iterator_instance.continuation_token diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py deleted file mode 100644 index 59a7835e4c8b..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core.exceptions import HttpResponseError -from azure.search.documents.aio import SearchClient -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClientAsync(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_get_document_count(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(is_async=True)) - async with client: - assert await client.get_document_count() == 10 - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_get_document(self, endpoint, index_name, index_batch): - client = SearchClient(endpoint, index_name, get_credential(is_async=True)) - async with client: - for hotel_id in range(1, 11): - result = await client.get_document(key=str(hotel_id)) - expected = index_batch["value"][hotel_id - 1] - assert result.get("hotelId") == expected.get("hotelId") - assert result.get("hotelName") == expected.get("hotelName") - assert result.get("description") == expected.get("description") - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_get_document_missing(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(is_async=True)) - async with client: - with pytest.raises(HttpResponseError): - await client.get_document(key="1000") diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py deleted file mode 100644 index 05ad3b2a6bdd..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py +++ /dev/null @@ -1,173 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -import time -from azure.core.exceptions import HttpResponseError -from azure.core.credentials import AzureKeyCredential -from azure.search.documents.aio import SearchIndexingBufferedSender, SearchClient -from devtools_testutils import AzureRecordedTestCase, get_credential -from devtools_testutils.aio import recorded_by_proxy_async -from search_service_preparer import SearchEnvVarPreparer, search_decorator - -TIME_TO_SLEEP = 3 - - -class TestSearchIndexingBufferedSenderAsync(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_search_client_index_buffered_sender(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) - batch_client = SearchIndexingBufferedSender( - endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60 - ) - try: - async with client: - async with batch_client: - doc_count = 10 - doc_count = await self._test_upload_documents_new(client, batch_client, doc_count) - doc_count = await self._test_upload_documents_existing(client, batch_client, doc_count) - doc_count = await self._test_delete_documents_existing(client, batch_client, doc_count) - doc_count = await self._test_delete_documents_missing(client, batch_client, doc_count) - doc_count = await self._test_merge_documents_existing(client, batch_client, doc_count) - doc_count = await self._test_merge_documents_missing(client, batch_client, doc_count) - doc_count = await self._test_merge_or_upload_documents(client, batch_client, doc_count) - finally: - await batch_client.close() - - async def _test_upload_documents_new(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - docs = [ - {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - await batch_client.upload_documents(docs) - doc_count += 2 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - for doc in docs: - result = await client.get_document(key=doc["hotelId"]) - assert result["hotelId"] == doc["hotelId"] - assert result["hotelName"] == doc["hotelName"] - assert result["rating"] == doc["rating"] - assert result["rooms"] == doc["rooms"] - return doc_count - - async def _test_upload_documents_existing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # add one new and one existing - docs = [ - {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - await batch_client.upload_documents(docs) - doc_count += 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - return doc_count - - async def _test_delete_documents_existing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - docs = [{"hotelId": "3"}, {"hotelId": "4"}] - await batch_client.delete_documents(docs) - doc_count -= 2 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - await client.get_document(key="3") - - with pytest.raises(HttpResponseError): - await client.get_document(key="4") - return doc_count - - async def _test_delete_documents_missing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # delete one existing and one missing - docs = [{"hotelId": "1003"}, {"hotelId": "2"}] - await batch_client.delete_documents(docs) - doc_count -= 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - with pytest.raises(HttpResponseError): - await client.get_document(key="1003") - with pytest.raises(HttpResponseError): - await client.get_document(key="2") - return doc_count - - async def _test_merge_documents_existing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] - await batch_client.merge_documents(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - result = await client.get_document(key="5") - assert result["rating"] == 1 - - result = await client.get_document(key="6") - assert result["rating"] == 2 - return doc_count - - async def _test_merge_documents_missing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # merge to one existing and one missing document - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - await batch_client.merge_documents(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - await client.get_document(key="1003") - - result = await client.get_document(key="1") - assert result["rating"] == 2 - return doc_count - - async def _test_merge_or_upload_documents(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # merge to one existing and one missing - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - await batch_client.merge_or_upload_documents(docs) - doc_count += 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - result = await client.get_document(key="1003") - assert result["rating"] == 1 - - result = await client.get_document(key="1") - assert result["rating"] == 2 - return doc_count diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py deleted file mode 100644 index c021c11c6fb8..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py +++ /dev/null @@ -1,169 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from pydoc import doc -import pytest -import time -from azure.core.exceptions import HttpResponseError -from azure.search.documents.aio import SearchClient -from devtools_testutils import AzureRecordedTestCase, get_credential -from devtools_testutils.aio import recorded_by_proxy_async -from search_service_preparer import SearchEnvVarPreparer, search_decorator - -TIME_TO_SLEEP = 3 - - -class TestSearchClientDocumentsAsync(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_search_client_index_document(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) - doc_count = 10 - async with client: - doc_count = await self._test_upload_documents_new(client, doc_count) - doc_count = await self._test_upload_documents_existing(client, doc_count) - doc_count = await self._test_delete_documents_existing(client, doc_count) - doc_count = await self._test_delete_documents_missing(client, doc_count) - doc_count = await self._test_merge_documents_existing(client, doc_count) - doc_count = await self._test_merge_documents_missing(client, doc_count) - doc_count = await self._test_merge_or_upload_documents(client, doc_count) - - async def _test_upload_documents_new(self, client, doc_count): - docs = [ - {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - results = await client.upload_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {201} - doc_count += len(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - for doc in docs: - result = await client.get_document(key=doc["hotelId"]) - assert result["hotelId"] == doc["hotelId"] - assert result["hotelName"] == doc["hotelName"] - assert result["rating"] == doc["rating"] - assert result["rooms"] == doc["rooms"] - return doc_count - - async def _test_upload_documents_existing(self, client, doc_count): - # add one new and one existing - docs = [ - {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - results = await client.upload_documents(docs) - assert len(results) == len(docs) - doc_count += 1 - assert set(x.status_code for x in results) == {200, 201} - return doc_count - - async def _test_delete_documents_existing(self, client, doc_count): - docs = [{"hotelId": "3"}, {"hotelId": "4"}] - results = await client.delete_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200} - doc_count -= len(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - await client.get_document(key="3") - - with pytest.raises(HttpResponseError): - await client.get_document(key="4") - return doc_count - - async def _test_delete_documents_missing(self, client, doc_count): - # delete one existing and one missing - docs = [{"hotelId": "1003"}, {"hotelId": "2"}] - results = await client.delete_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200} - doc_count -= 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - await client.get_document(key="1003") - - with pytest.raises(HttpResponseError): - await client.get_document(key="2") - return doc_count - - async def _test_merge_documents_existing(self, client, doc_count): - docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] - results = await client.merge_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200} - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - result = await client.get_document(key="5") - assert result["rating"] == 1 - - result = await client.get_document(key="6") - assert result["rating"] == 2 - return doc_count - - async def _test_merge_documents_missing(self, client, doc_count): - # merge to one existing and one missing document - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - results = await client.merge_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200, 404} - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - await client.get_document(key="1003") - - result = await client.get_document(key="1") - assert result["rating"] == 2 - return doc_count - - async def _test_merge_or_upload_documents(self, client, doc_count): - # merge to one existing and one missing - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - results = await client.merge_or_upload_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200, 201} - doc_count += 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert await client.get_document_count() == doc_count - - result = await client.get_document(key="1003") - assert result["rating"] == 1 - - result = await client.get_document(key="1") - assert result["rating"] == 2 - return doc_count diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py deleted file mode 100644 index e7e31c666197..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py +++ /dev/null @@ -1,160 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import pytest - -from azure.core.exceptions import HttpResponseError -from azure.search.documents.aio import SearchClient -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestClientTestAsync(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_search_client(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) - async with client: - await self._test_get_search_simple(client) - await self._test_get_search_simple_with_top(client) - await self._test_get_search_filter(client) - await self._test_get_search_filter_array(client) - await self._test_get_search_counts(client) - await self._test_get_search_coverage(client) - await self._test_get_search_facets_none(client) - await self._test_get_search_facets_result(client) - await self._test_autocomplete(client) - await self._test_suggest(client) - - async def _test_get_search_simple(self, client): - results = [] - async for x in await client.search(search_text="hotel"): - results.append(x) - assert len(results) == 7 - - results = [] - async for x in await client.search(search_text="motel"): - results.append(x) - assert len(results) == 2 - - async def _test_get_search_simple_with_top(self, client): - results = [] - async for x in await client.search(search_text="hotel", top=3): - results.append(x) - assert len(results) == 3 - - results = [] - async for x in await client.search(search_text="motel", top=3): - results.append(x) - assert len(results) == 2 - - async def _test_get_search_filter(self, client): - results = [] - select = ["hotelName", "category", "description"] - async for x in await client.search( - search_text="WiFi", - filter="category eq 'Budget'", - select=",".join(select), - order_by="hotelName desc", - ): - results.append(x) - assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) - expected = { - "category", - "hotelName", - "description", - "@search.score", - "@search.reranker_score", - "@search.highlights", - "@search.captions", - "@search.document_debug_info", - "@search.reranker_boosted_score", - } - assert all(set(x) == expected for x in results) - assert all(x["category"] == "Budget" for x in results) - - async def _test_get_search_filter_array(self, client): - results = [] - select = ["hotelName", "category", "description"] - async for x in await client.search( - search_text="WiFi", - filter="category eq 'Budget'", - select=select, - order_by="hotelName desc", - ): - results.append(x) - assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) - expected = { - "category", - "hotelName", - "description", - "@search.score", - "@search.reranker_score", - "@search.highlights", - "@search.captions", - "@search.document_debug_info", - "@search.reranker_boosted_score", - } - assert all(set(x) == expected for x in results) - assert all(x["category"] == "Budget" for x in results) - - async def _test_get_search_counts(self, client): - results = await client.search(search_text="hotel") - assert await results.get_count() is None - - results = await client.search(search_text="hotel", include_total_count=True) - assert await results.get_count() == 7 - - async def _test_get_search_coverage(self, client): - results = await client.search(search_text="hotel") - assert await results.get_coverage() is None - - results = await client.search(search_text="hotel", minimum_coverage=50.0) - cov = await results.get_coverage() - assert isinstance(cov, float) - assert cov >= 50.0 - - async def _test_get_search_facets_none(self, client): - select = ("hotelName", "category", "description") - results = await client.search(search_text="WiFi", select=",".join(select)) - assert await results.get_facets() is None - - async def _test_get_search_facets_result(self, client): - select = ("hotelName", "category", "description") - results = await client.search(search_text="WiFi", facets=["category"], select=",".join(select)) - assert await results.get_facets() == { - "category": [ - {"value": "Budget", "count": 4}, - {"value": "Luxury", "count": 1}, - ] - } - - async def _test_autocomplete(self, client): - results = await client.autocomplete(search_text="mot", suggester_name="sg") - assert results == [{"text": "motel", "query_plus_text": "motel"}] - - async def _test_suggest(self, client): - results = await client.suggest(search_text="mot", suggester_name="sg") - assert results == [ - {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, - {"hotelId": "9", "text": "Secret Point Motel"}, - ] - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_large.json") - @recorded_by_proxy_async - async def test_search_client_large(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(is_async=True)) - async with client: - await self._test_get_search_simple_large(client) - - async def _test_get_search_simple_large(self, client): - results = [] - async for x in await client.search(search_text=""): - results.append(x) - assert len(results) == 60 diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py deleted file mode 100644 index 6fdfe85ae2ba..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py +++ /dev/null @@ -1,111 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from unicodedata import name -import pytest - -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes.aio import SearchIndexClient -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential -from azure.search.documents.indexes.models import ( - AnalyzeTextOptions, - CorsOptions, - SearchIndex, - ScoringProfile, - SimpleField, - SearchFieldDataType, - SearchAlias, -) - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClientAlias(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_alias(self, endpoint): - client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - aliases = ["resort", "motel"] - - async with client: - index_name = await client.list_index_names().__anext__() - await self._test_list_aliases_empty(client) - await self._test_create_alias(client, aliases[0], index_name) - - await self._test_create_or_update_alias(client, aliases[1], index_name) - - # point an old alias to a new index - new_index_name = "hotel" - await self._test_update_alias_to_new_index(client, aliases[1], new_index_name, index_name) - - await self._test_get_alias(client, aliases) - - await self._test_list_aliases(client, aliases) - await self._test_delete_aliases(client) - - async def _test_list_aliases_empty(self, client): - result = client.list_aliases() - with pytest.raises(StopAsyncIteration): - await result.__anext__() - - async def _test_create_alias(self, client, alias_name, index_name): - alias = SearchAlias(name=alias_name, indexes=[index_name]) - result = await client.create_alias(alias) - assert result.name == alias_name - assert set(result.indexes) == {index_name} - - async def _test_create_or_update_alias(self, client, alias_name, index_name): - alias = SearchAlias(name=alias_name, indexes=[index_name]) - result = await client.create_or_update_alias(alias) - assert result.name == alias_name - assert set(result.indexes) == {index_name} - - async def _test_update_alias_to_new_index(self, client, alias_name, new_index, old_index): - await self._create_index(client, new_index) - alias = SearchAlias(name=alias_name, indexes=[new_index]) - result = await client.create_or_update_alias(alias) - - assert result.name == alias_name - assert result.indexes[0] != old_index - assert result.indexes[0] == new_index - - async def _test_get_alias(self, client, aliases): - for alias in aliases: - result = await client.get_alias(alias) - assert result - assert result.name == alias - - async def _test_list_aliases(self, client, aliases): - result = {alias async for alias in client.list_alias_names()} - assert result == set(aliases) - - async def _test_delete_aliases(self, client): - aliases = [alias async for alias in client.list_aliases()] - - for alias in aliases: - await client.delete_alias(alias) - with pytest.raises(HttpResponseError): - result = await client.get_alias(alias) - - async def _create_index(self, client, index_name): - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=index_name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = await client.create_index(index) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py deleted file mode 100644 index 473555cf29a1..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py +++ /dev/null @@ -1,114 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -import asyncio -import functools -import pytest -from unittest import mock -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import ApiVersion -from azure.search.documents.aio import SearchClient -from azure.search.documents.indexes.aio import SearchIndexClient, SearchIndexerClient -from devtools_testutils import trim_kwargs_from_test_function - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - - -def await_prepared_test(test_fn): - """Synchronous wrapper for async test methods. Used to avoid making changes - upstream to AbstractPreparer (which doesn't await the functions it wraps) - """ - - @functools.wraps(test_fn) - def run(test_class_instance, *args, **kwargs): - trim_kwargs_from_test_function(test_fn, kwargs) - loop = asyncio.get_event_loop() - return loop.run_until_complete(test_fn(test_class_instance, **kwargs)) - - return run - - -class TestSearchIndexClient: - def test_index_init(self): - client = SearchIndexClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_index_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_get_search_client(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - - def test_get_search_client_inherit_api_version(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential, api_version=ApiVersion.V2020_06_30) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - assert search_client._api_version == ApiVersion.V2020_06_30 - - def test_index_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexClient(12345, credential) - - -class TestSearchIndexerClient: - def test_indexer_init(self): - client = SearchIndexerClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexerClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexerClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexerClient(12345, credential) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py deleted file mode 100644 index e5d15a396ff5..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py +++ /dev/null @@ -1,120 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator -from azure.search.documents.indexes.models import ( - SearchIndexerDataSourceConnection, - SearchIndexerDataContainer, -) -from azure.search.documents.indexes.aio import SearchIndexerClient - - -class TestSearchClientDataSourcesAsync(AzureRecordedTestCase): - def _create_data_source_connection(self, cs, name): - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name=name, type="azureblob", connection_string=cs, container=container - ) - return data_source_connection - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_data_source(self, endpoint, **kwargs): - storage_cs = kwargs.get("search_storage_connection_string") - client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - async with client: - await self._test_create_datasource(client, storage_cs) - await self._test_delete_datasource(client, storage_cs) - await self._test_get_datasource(client, storage_cs) - await self._test_list_datasources(client, storage_cs) - await self._test_create_or_update_datasource(client, storage_cs) - await self._test_create_or_update_datasource_if_unchanged(client, storage_cs) - await self._test_delete_datasource_if_unchanged(client, storage_cs) - - async def _test_create_datasource(self, client, storage_cs): - ds_name = "create" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - result = await client.create_data_source_connection(data_source_connection) - assert result.name == ds_name - assert result.type == "azureblob" - - async def _test_delete_datasource(self, client, storage_cs): - ds_name = "delete" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - await client.create_data_source_connection(data_source_connection) - expected_count = len(await client.get_data_source_connections()) - 1 - await client.delete_data_source_connection(ds_name) - assert len(await client.get_data_source_connections()) == expected_count - - async def _test_get_datasource(self, client, storage_cs): - ds_name = "get" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - await client.create_data_source_connection(data_source_connection) - result = await client.get_data_source_connection(ds_name) - assert result.name == ds_name - - async def _test_list_datasources(self, client, storage_cs): - data_source_connection1 = self._create_data_source_connection(storage_cs, "list") - data_source_connection2 = self._create_data_source_connection(storage_cs, "list2") - await client.create_data_source_connection(data_source_connection1) - await client.create_data_source_connection(data_source_connection2) - result = await client.get_data_source_connections() - assert isinstance(result, list) - assert set(x.name for x in result).intersection(set(["list", "list2"])) == set(["list", "list2"]) - - async def _test_create_or_update_datasource(self, client, storage_cs): - ds_name = "cou" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - await client.create_data_source_connection(data_source_connection) - expected_count = len(await client.get_data_source_connections()) - data_source_connection.description = "updated" - await client.create_or_update_data_source_connection(data_source_connection) - assert len(await client.get_data_source_connections()) == expected_count - result = await client.get_data_source_connection(ds_name) - assert result.name == ds_name - assert result.description == "updated" - - async def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): - ds_name = "couunch" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - created = await client.create_data_source_connection(data_source_connection) - etag = created.e_tag - - # Now update the data source connection - data_source_connection.description = "updated" - await client.create_or_update_data_source_connection(data_source_connection) - - # prepare data source connection - data_source_connection.e_tag = etag # reset to the original data source connection - data_source_connection.description = "changed" - with pytest.raises(HttpResponseError): - await client.create_or_update_data_source_connection( - data_source_connection, match_condition=MatchConditions.IfNotModified - ) - - async def _test_delete_datasource_if_unchanged(self, client, storage_cs): - ds_name = "delunch" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - created = await client.create_data_source_connection(data_source_connection) - etag = created.e_tag - - # Now update the data source connection - data_source_connection.description = "updated" - await client.create_or_update_data_source_connection(data_source_connection) - - # prepare data source connection - data_source_connection.e_tag = etag # reset to the original data source connection - with pytest.raises(HttpResponseError): - await client.delete_data_source_connection( - data_source_connection, match_condition=MatchConditions.IfNotModified - ) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py deleted file mode 100644 index 8afea2e16425..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py +++ /dev/null @@ -1,190 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import pytest - -from azure.core.exceptions import HttpResponseError -from azure.core import MatchConditions -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator -from azure.search.documents.indexes.aio import SearchIndexClient -from azure.search.documents.indexes.models import ( - AnalyzeTextOptions, - CorsOptions, - SearchIndex, - ScoringProfile, - SimpleField, - SearchFieldDataType, -) - - -class TestSearchIndexClientAsync(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema=None, index_batch=None) - @recorded_by_proxy_async - async def test_search_index_client(self, endpoint, index_name): - client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - index_name = "hotels" - async with client: - await self._test_get_service_statistics(client) - await self._test_list_indexes_empty(client) - await self._test_create_index(client, index_name) - await self._test_list_indexes(client, index_name) - await self._test_get_index(client, index_name) - await self._test_get_index_statistics(client, index_name) - await self._test_delete_indexes_if_unchanged(client) - await self._test_create_or_update_index(client) - await self._test_create_or_update_indexes_if_unchanged(client) - await self._test_analyze_text(client, index_name) - await self._test_delete_indexes(client) - - async def _test_get_service_statistics(self, client): - result = await client.get_service_statistics() - assert isinstance(result, dict) - assert set(result.keys()) == {"counters", "limits"} - - async def _test_list_indexes_empty(self, client): - result = client.list_indexes() - with pytest.raises(StopAsyncIteration): - await result.__anext__() - - async def _test_create_index(self, client, index_name): - fields = fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=index_name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = await client.create_index(index) - assert result.name == "hotels" - assert result.scoring_profiles[0].name == scoring_profile.name - assert result.cors_options.allowed_origins == cors_options.allowed_origins - assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds - - async def _test_list_indexes(self, client, index_name): - result = client.list_indexes() - first = await result.__anext__() - assert first.name == index_name - with pytest.raises(StopAsyncIteration): - await result.__anext__() - - async def _test_get_index(self, client, index_name): - result = await client.get_index(index_name) - assert result.name == index_name - - async def _test_get_index_statistics(self, client, index_name): - result = await client.get_index_statistics(index_name) - keys = set(result.keys()) - assert "document_count" in keys - assert "storage_size" in keys - assert "vector_index_size" in keys - - async def _test_delete_indexes_if_unchanged(self, client): - # First create an index - name = "hotels-del-unchanged" - fields = [ - {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, - {"name": "baseRate", "type": "Edm.Double"}, - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = await client.create_index(index) - etag = result.e_tag - # get eTag and update - index.scoring_profiles = [] - await client.create_or_update_index(index) - - index.e_tag = etag - with pytest.raises(HttpResponseError): - await client.delete_index(index, match_condition=MatchConditions.IfNotModified) - - async def _test_create_or_update_index(self, client): - name = "hotels-cou" - fields = fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profiles = [] - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = await client.create_or_update_index(index=index) - assert len(result.scoring_profiles) == 0 - assert result.cors_options.allowed_origins == cors_options.allowed_origins - assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = await client.create_or_update_index(index=index) - assert result.scoring_profiles[0].name == scoring_profile.name - assert result.cors_options.allowed_origins == cors_options.allowed_origins - assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds - - async def _test_create_or_update_indexes_if_unchanged(self, client): - # First create an index - name = "hotels-coa-unchanged" - fields = [ - {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, - {"name": "baseRate", "type": "Edm.Double"}, - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = await client.create_index(index) - etag = result.e_tag - # get eTag and update - index.scoring_profiles = [] - await client.create_or_update_index(index) - - index.e_tag = etag - with pytest.raises(HttpResponseError): - await client.create_or_update_index(index, match_condition=MatchConditions.IfNotModified) - - async def _test_analyze_text(self, client, index_name): - analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") - result = await client.analyze_text(index_name, analyze_request) - assert len(result.tokens) == 2 - - async def _test_delete_indexes(self, client): - result = client.list_indexes() - async for index in result: - await client.delete_index(index.name) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py deleted file mode 100644 index 97308ba3ad33..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py +++ /dev/null @@ -1,217 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential -from search_service_preparer import SearchEnvVarPreparer, search_decorator -from azure.search.documents.indexes.models import ( - EntityLinkingSkill, - EntityRecognitionSkill, - EntityRecognitionSkillVersion, - InputFieldMappingEntry, - OutputFieldMappingEntry, - SearchIndexerSkillset, - SentimentSkill, - SentimentSkillVersion, -) -from azure.search.documents.indexes.aio import SearchIndexerClient - - -class TestSearchClientSkillsets(AzureRecordedTestCase): - @pytest.mark.skip("The skills are deprecated") - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_skillset_crud(self, endpoint): - client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - async with client: - await self._test_create_skillset(client) - await self._test_get_skillset(client) - await self._test_get_skillsets(client) - await self._test_create_or_update_skillset(client) - await self._test_create_or_update_skillset_if_unchanged(client) - await self._test_create_or_update_skillset_inplace(client) - await self._test_delete_skillset_if_unchanged(client) - await self._test_delete_skillset(client) - - async def _test_create_skillset(self, client): - name = "test-ss-create" - s1 = EntityRecognitionSkill( - name="skill1", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], - description="Skill Version 1", - model_version="1", - include_typeless_entities=True, - ) - - s2 = EntityRecognitionSkill( - name="skill2", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], - skill_version=EntityRecognitionSkillVersion.LATEST, - description="Skill Version 3", - model_version="3", - include_typeless_entities=True, - ) - s3 = SentimentSkill( - name="skill3", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], - skill_version=SentimentSkillVersion.V1, - description="Sentiment V1", - include_opinion_mining=True, - ) - - s4 = SentimentSkill( - name="skill4", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4")], - skill_version=SentimentSkillVersion.V3, - description="Sentiment V3", - include_opinion_mining=True, - ) - - s5 = EntityLinkingSkill( - name="skill5", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="entities", target_name="entitiesS5")], - minimum_precision=0.5, - ) - - skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s3, s4, s5]), description="desc") - result = await client.create_skillset(skillset) - - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc" - assert result.e_tag - assert len(result.skills) == 5 - assert isinstance(result.skills[0], EntityRecognitionSkill) - assert result.skills[0].skill_version == EntityRecognitionSkillVersion.V1 - assert isinstance(result.skills[1], EntityRecognitionSkill) - assert result.skills[1].skill_version == EntityRecognitionSkillVersion.V3 - assert isinstance(result.skills[2], SentimentSkill) - assert result.skills[2].skill_version == SentimentSkillVersion.V1 - assert isinstance(result.skills[3], SentimentSkill) - assert result.skills[3].skill_version == SentimentSkillVersion.V3 - assert isinstance(result.skills[4], EntityLinkingSkill) - assert result.skills[4].minimum_precision == 0.5 - - assert len(await client.get_skillsets()) == 1 - await client.reset_skills(result, [x.name for x in result.skills]) - - async def _test_get_skillset(self, client): - name = "test-ss-get" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") - await client.create_skillset(skillset) - result = await client.get_skillset(name) - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc" - assert result.e_tag - assert len(result.skills) == 1 - assert isinstance(result.skills[0], EntityRecognitionSkill) - - async def _test_get_skillsets(self, client): - name1 = "test-ss-list-1" - name2 = "test-ss-list-2" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name1, skills=list([s]), description="desc1") - await client.create_skillset(skillset1) - skillset2 = SearchIndexerSkillset(name=name2, skills=list([s]), description="desc2") - await client.create_skillset(skillset2) - result = await client.get_skillsets() - assert isinstance(result, list) - assert all(isinstance(x, SearchIndexerSkillset) for x in result) - assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) - - async def _test_create_or_update_skillset(self, client): - name = "test-ss-create-or-update" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") - await client.create_or_update_skillset(skillset1) - expected_count = len(await client.get_skillsets()) - skillset2 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc2") - await client.create_or_update_skillset(skillset2) - assert len(await client.get_skillsets()) == expected_count - - result = await client.get_skillset(name) - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc2" - - async def _test_create_or_update_skillset_inplace(self, client): - name = "test-ss-create-or-update-inplace" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") - ss = await client.create_or_update_skillset(skillset1) - expected_count = len(await client.get_skillsets()) - skillset2 = SearchIndexerSkillset(name=name, skills=[s], description="desc2", skillset=ss) - await client.create_or_update_skillset(skillset2) - assert len(await client.get_skillsets()) == expected_count - - result = await client.get_skillset(name) - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc2" - - async def _test_create_or_update_skillset_if_unchanged(self, client): - name = "test-ss-create-or-update-unchanged" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") - ss = await client.create_or_update_skillset(skillset1) - - ss.e_tag = "changed_etag" - - with pytest.raises(HttpResponseError): - await client.create_or_update_skillset(ss, match_condition=MatchConditions.IfNotModified) - - async def _test_delete_skillset_if_unchanged(self, client): - name = "test-ss-deleted-unchanged" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") - result = await client.create_skillset(skillset) - etag = result.e_tag - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="updated") - updated = await client.create_or_update_skillset(skillset1) - updated.e_tag = etag - - with pytest.raises(HttpResponseError): - await client.delete_skillset(updated, match_condition=MatchConditions.IfNotModified) - - async def _test_delete_skillset(self, client): - result = await client.get_skillset_names() - for skillset in result: - await client.delete_skillset(skillset) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py deleted file mode 100644 index 41a92e92f91c..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py +++ /dev/null @@ -1,147 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest - -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes.aio import SearchIndexClient -from azure.search.documents.indexes.models import SynonymMap -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils import AzureRecordedTestCase, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClientSynonymMaps(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_synonym_map(self, endpoint): - client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - async with client: - await self._test_create_synonym_map(client) - await self._test_delete_synonym_map(client) - await self._test_delete_synonym_map_if_unchanged(client) - await self._test_get_synonym_map(client) - await self._test_get_synonym_maps(client) - await self._test_create_or_update_synonym_map(client) - - async def _test_create_synonym_map(self, client): - expected = len(await client.get_synonym_maps()) + 1 - name = "synmap-create" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - result = await client.create_synonym_map(synonym_map) - assert isinstance(result, SynonymMap) - assert result.name == name - assert result.synonyms == [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - assert len(await client.get_synonym_maps()) == expected - await client.delete_synonym_map(name) - - async def _test_delete_synonym_map(self, client): - name = "synmap-del" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - result = await client.create_synonym_map(synonym_map) - expected = len(await client.get_synonym_maps()) - 1 - await client.delete_synonym_map(name) - assert len(await client.get_synonym_maps()) == expected - - async def _test_delete_synonym_map_if_unchanged(self, client): - name = "synmap-delunch" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - result = await client.create_synonym_map(synonym_map) - etag = result.e_tag - - synonym_map.synonyms = "\n".join( - [ - "Washington, Wash. => WA", - ] - ) - await client.create_or_update_synonym_map(synonym_map) - - result.e_tag = etag - with pytest.raises(HttpResponseError): - await client.delete_synonym_map(result, match_condition=MatchConditions.IfNotModified) - await client.delete_synonym_map(name) - - async def _test_get_synonym_map(self, client): - expected = len(await client.get_synonym_maps()) + 1 - name = "synmap-get" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - await client.create_synonym_map(synonym_map) - assert len(await client.get_synonym_maps()) == expected - result = await client.get_synonym_map(name) - assert isinstance(result, SynonymMap) - assert result.name == name - assert result.synonyms == [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - await client.delete_synonym_map(name) - - async def _test_get_synonym_maps(self, client): - name1 = "synmap-list1" - name2 = "synmap-list2" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map_1 = SynonymMap(name=name1, synonyms=synonyms) - await client.create_synonym_map(synonym_map_1) - synonyms = [ - "Washington, Wash. => WA", - ] - synonym_map_2 = SynonymMap(name=name2, synonyms=synonyms) - await client.create_synonym_map(synonym_map_2) - result = await client.get_synonym_maps() - assert isinstance(result, list) - assert all(isinstance(x, SynonymMap) for x in result) - expected = set([name1, name2]) - assert set(x.name for x in result).intersection(expected) == expected - await client.delete_synonym_map(name1) - await client.delete_synonym_map(name2) - - async def _test_create_or_update_synonym_map(self, client): - expected = len(await client.get_synonym_maps()) + 1 - name = "synmap-cou" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - await client.create_synonym_map(synonym_map) - assert len(await client.get_synonym_maps()) == expected - synonym_map.synonyms = [ - "Washington, Wash. => WA", - ] - await client.create_or_update_synonym_map(synonym_map) - assert len(await client.get_synonym_maps()) == expected - result = await client.get_synonym_map(name) - assert isinstance(result, SynonymMap) - assert result.name == name - assert result.synonyms == [ - "Washington, Wash. => WA", - ] - await client.delete_synonym_map(name) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py deleted file mode 100644 index 31cc3aa6f6a5..000000000000 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py +++ /dev/null @@ -1,154 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes.aio import SearchIndexClient, SearchIndexerClient -from azure.search.documents.indexes.models import ( - SearchIndex, - SearchIndexer, - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, -) -from devtools_testutils import AzureRecordedTestCase, get_credential -from devtools_testutils.aio import recorded_by_proxy_async - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchIndexerClientTestAsync(AzureRecordedTestCase): - @pytest.mark.skip("fails because connection string of storage is disabled") - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy_async - async def test_search_indexers(self, endpoint, **kwargs): - storage_cs = kwargs.get("search_storage_connection_string") - container_name = kwargs.get("search_storage_container_name") - client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - index_client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) - async with client: - async with index_client: - await self._test_create_indexer(client, index_client, storage_cs, container_name) - await self._test_delete_indexer(client, index_client, storage_cs, container_name) - await self._test_get_indexer(client, index_client, storage_cs, container_name) - await self._test_list_indexer(client, index_client, storage_cs, container_name) - await self._test_create_or_update_indexer(client, index_client, storage_cs, container_name) - await self._test_reset_indexer(client, index_client, storage_cs, container_name) - await self._test_run_indexer(client, index_client, storage_cs, container_name) - await self._test_get_indexer_status(client, index_client, storage_cs, container_name) - await self._test_create_or_update_indexer_if_unchanged(client, index_client, storage_cs, container_name) - await self._test_delete_indexer_if_unchanged(client, index_client, storage_cs, container_name) - - async def _prepare_indexer(self, client, index_client, storage_cs, name, container_name): - data_source_connection = SearchIndexerDataSourceConnection( - name=f"{name}-ds", - type="azureblob", - connection_string=storage_cs, - container=SearchIndexerDataContainer(name=container_name), - ) - ds = await client.create_data_source_connection(data_source_connection) - - fields = [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}] - index = SearchIndex(name=f"{name}-hotels", fields=fields) - ind = await index_client.create_index(index) - return SearchIndexer(name=name, data_source_name=ds.name, target_index_name=ind.name) - - async def _test_create_indexer(self, client, index_client, storage_cs, container_name): - name = "create" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - result = await client.create_indexer(indexer) - assert result.name == name - assert result.target_index_name == f"{name}-hotels" - assert result.data_source_name == f"{name}-ds" - - async def _test_delete_indexer(self, client, index_client, storage_cs, container_name): - name = "delete" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - await client.create_indexer(indexer) - expected = len(await client.get_indexers()) - 1 - await client.delete_indexer(name) - assert len(await client.get_indexers()) == expected - - async def _test_get_indexer(self, client, index_client, storage_cs, container_name): - name = "get" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - await client.create_indexer(indexer) - result = await client.get_indexer(name) - assert result.name == name - - async def _test_list_indexer(self, client, index_client, storage_cs, container_name): - name1 = "list1" - name2 = "list2" - indexer1 = await self._prepare_indexer(client, index_client, storage_cs, name1, container_name) - indexer2 = await self._prepare_indexer(client, index_client, storage_cs, name2, container_name) - await client.create_indexer(indexer1) - await client.create_indexer(indexer2) - result = await client.get_indexers() - assert isinstance(result, list) - assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) - - async def _test_create_or_update_indexer(self, client, index_client, storage_cs, container_name): - name = "cou" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - await client.create_indexer(indexer) - expected = len(await client.get_indexers()) - indexer.description = "updated" - await client.create_or_update_indexer(indexer) - assert len(await client.get_indexers()) == expected - result = await client.get_indexer(name) - assert result.name == name - assert result.description == "updated" - - async def _test_reset_indexer(self, client, index_client, storage_cs, container_name): - name = "reset" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - await client.create_indexer(indexer) - await client.reset_indexer(name) - assert (await client.get_indexer_status(name)).last_result.status.lower() in ( - "inprogress", - "reset", - ) - - async def _test_run_indexer(self, client, index_client, storage_cs, container_name): - name = "run" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - await client.create_indexer(indexer) - await client.run_indexer(name) - assert (await client.get_indexer_status(name)).status == "running" - - async def _test_get_indexer_status(self, client, index_client, storage_cs, container_name): - name = "get-status" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - await client.create_indexer(indexer) - status = await client.get_indexer_status(name) - assert status.status is not None - - async def _test_create_or_update_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): - name = "couunch" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - created = await client.create_indexer(indexer) - etag = created.e_tag - - indexer.description = "updated" - await client.create_or_update_indexer(indexer) - - indexer.e_tag = etag - with pytest.raises(HttpResponseError): - await client.create_or_update_indexer(indexer, match_condition=MatchConditions.IfNotModified) - - async def _test_delete_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): - name = "delunch" - indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) - result = await client.create_indexer(indexer) - etag = result.e_tag - - indexer.description = "updated" - await client.create_or_update_indexer(indexer) - - indexer.e_tag = etag - with pytest.raises(HttpResponseError): - await client.delete_indexer(indexer, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/conftest.py b/sdk/search/azure-search-documents/tests/conftest.py deleted file mode 100644 index 0ecac854421a..000000000000 --- a/sdk/search/azure-search-documents/tests/conftest.py +++ /dev/null @@ -1,36 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -import sys -import pytest -from devtools_testutils import test_proxy, remove_batch_sanitizers -from devtools_testutils.sanitizers import ( - add_remove_header_sanitizer, - add_general_regex_sanitizer, -) - -# Ignore async tests for Python < 3.5 -collect_ignore = [] -if sys.version_info < (3, 5): - collect_ignore.append("async_tests") - - -@pytest.fixture(scope="session", autouse=True) -def add_sanitizers(test_proxy): - add_remove_header_sanitizer(headers="api-key") - - # Ensure all search service endpoint names are mocked to "test-service" - add_general_regex_sanitizer( - value="://fakesearchendpoint.search.windows.net", - regex=r"://(.+).search.windows.net", - ) - # Remove storage connection strings from recordings - add_general_regex_sanitizer(value="AccountKey=FAKE;", regex=r"AccountKey=([^;]+);") - # Remove storage account names from recordings - add_general_regex_sanitizer(value="AccountName=fakestoragecs;", regex=r"AccountName=([^;]+);") - # Remove the following sanitizers since certain fields are needed in tests and are non-sensitive: - # - AZSDK3493: $..name - remove_batch_sanitizers(["AZSDK3493"]) diff --git a/sdk/search/azure-search-documents/tests/hotel_large.json b/sdk/search/azure-search-documents/tests/hotel_large.json deleted file mode 100644 index 10f286f65c0d..000000000000 --- a/sdk/search/azure-search-documents/tests/hotel_large.json +++ /dev/null @@ -1,1504 +0,0 @@ -{ - "value": [ - { - "@search.action": "upload", - "hotelId": "1", - "hotelName": "Fancy Stay", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "2", - "hotelName": "Roach Motel", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "3", - "hotelName": "EconoStay", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "4", - "hotelName": "Express Rooms", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "5", - "hotelName": "Comfy Place", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "6", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "7", - "hotelName": "Modern Stay", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "8", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "9", - "hotelName": "Secret Point Motel", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "10", - "hotelName": "Countryside Hotel", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "11", - "hotelName": "Fancy Stay 1", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "12", - "hotelName": "Roach Motel 1", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "13", - "hotelName": "EconoStay 1", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "14", - "hotelName": "Express Rooms 1", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "15", - "hotelName": "Comfy Place 1", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "16", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "17", - "hotelName": "Modern Stay1", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "18", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "19", - "hotelName": "Secret Point Motel 1", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "20", - "hotelName": "Countryside Hotel 1", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "21", - "hotelName": "Fancy Stay 2", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "22", - "hotelName": "Roach Motel2", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "23", - "hotelName": "EconoStay2", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "24", - "hotelName": "Express Rooms2", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "25", - "hotelName": "Comfy Place2", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "26", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "27", - "hotelName": "Modern Stay2", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "28", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "29", - "hotelName": "Secret Point Motel2", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "30", - "hotelName": "Countryside Hotel 2", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "31", - "hotelName": "Fancy Stay3", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "32", - "hotelName": "Roach Motel3", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "33", - "hotelName": "EconoStay3", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "34", - "hotelName": "Express Rooms3", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "35", - "hotelName": "Comfy Place3", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "36", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "37", - "hotelName": "Modern Stay3", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "38", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "39", - "hotelName": "Secret Point Motel3", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "40", - "hotelName": "Countryside Hotel", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "41", - "hotelName": "Fancy Stay4", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "42", - "hotelName": "Roach Motel4", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "43", - "hotelName": "EconoStay4", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "44", - "hotelName": "Express Rooms4", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "45", - "hotelName": "Comfy Place4", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "46", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "47", - "hotelName": "Modern Stay4", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "48", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "49", - "hotelName": "Secret Point Motel4", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "50", - "hotelName": "Countryside Hotel", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "51", - "hotelName": "Fancy Stay5", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "52", - "hotelName": "Roach Motel5", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "53", - "hotelName": "EconoStay5", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "54", - "hotelName": "Express Rooms5", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "55", - "hotelName": "Comfy Place5", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "56", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "57", - "hotelName": "Modern Stay5", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "58", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "59", - "hotelName": "Secret Point Motel5", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "60", - "hotelName": "Countryside Hotel 5", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - } - ] - } \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/hotel_schema.json b/sdk/search/azure-search-documents/tests/hotel_schema.json deleted file mode 100644 index 606379345d48..000000000000 --- a/sdk/search/azure-search-documents/tests/hotel_schema.json +++ /dev/null @@ -1,288 +0,0 @@ -{ - "name": "drgqefsg", - "fields": [ - { - "name": "hotelId", - "type": "Edm.String", - "key": true, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "hotelName", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": false - }, - { - "name": "description", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "en.lucene" - }, - { - "name": "descriptionFr", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "fr.lucene" - }, - { - "name": "category", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "tags", - "type": "Collection(Edm.String)", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": false, - "facetable": true - }, - { - "name": "parkingIncluded", - "type": "Edm.Boolean", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "smokingAllowed", - "type": "Edm.Boolean", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "lastRenovationDate", - "type": "Edm.DateTimeOffset", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "rating", - "type": "Edm.Int32", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "location", - "type": "Edm.GeographyPoint", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": true, - "facetable": false - }, - { - "name": "address", - "type": "Edm.ComplexType", - "fields": [ - { - "name": "streetAddress", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false - }, - { - "name": "city", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "stateProvince", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "country", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "postalCode", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - } - ] - }, - { - "name": "rooms", - "type": "Collection(Edm.ComplexType)", - "fields": [ - { - "name": "description", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "en.lucene" - }, - { - "name": "descriptionFr", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "fr.lucene" - }, - { - "name": "type", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": false, - "facetable": true - }, - { - "name": "baseRate", - "type": "Edm.Double", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": false, - "facetable": true - }, - { - "name": "bedOptions", - "type": "Edm.String", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": false, - "facetable": true - }, - { - "name": "sleepsCount", - "type": "Edm.Int32", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": false, - "facetable": true - }, - { - "name": "smokingAllowed", - "type": "Edm.Boolean", - "key": false, - "retrievable": true, - "searchable": false, - "filterable": true, - "sortable": false, - "facetable": true - }, - { - "name": "tags", - "type": "Collection(Edm.String)", - "key": false, - "retrievable": true, - "searchable": true, - "filterable": true, - "sortable": false, - "facetable": true - } - ] - } - ], - "scoringProfiles": [ - { - "name": "nearest", - "functions": [ - { - "type": "distance", - "distance": { - "referencePointParameter": "myloc", - "boostingDistance": 100.0 - }, - "fieldName": "location", - "boost": 2.0 - } - ], - "functionAggregation": "sum" - } - ], - "suggesters": [ - { - "name": "sg", - "sourceFields": [ - "description", - "hotelName" - ], - "searchMode": "analyzingInfixMatching" - } - ] -} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/hotel_small.json b/sdk/search/azure-search-documents/tests/hotel_small.json deleted file mode 100644 index 6ea1027a61e3..000000000000 --- a/sdk/search/azure-search-documents/tests/hotel_small.json +++ /dev/null @@ -1,254 +0,0 @@ -{ - "value": [ - { - "@search.action": "upload", - "hotelId": "1", - "hotelName": "Fancy Stay", - "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "category": "Luxury", - "tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": false, - "lastRenovationDate": "2010-06-27T00:00:00+00:00", - "rating": 5, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "2", - "hotelName": "Roach Motel", - "description": "Cheapest hotel in town. Infact, a motel.", - "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", - "category": "Budget", - "tags": [ - "motel", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": true, - "lastRenovationDate": "1982-04-28T00:00:00+00:00", - "rating": 1, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "3", - "hotelName": "EconoStay", - "description": "Very popular hotel in town", - "descriptionFr": "Hôtel le plus populaire en ville", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 46.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "4", - "hotelName": "Express Rooms", - "description": "Pretty good hotel", - "descriptionFr": "Assez bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "1995-07-01T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "5", - "hotelName": "Comfy Place", - "description": "Another good hotel", - "descriptionFr": "Un autre bon hôtel", - "category": "Budget", - "tags": [ - "wifi", - "budget" - ], - "parkingIncluded": true, - "smokingAllowed": false, - "lastRenovationDate": "2012-08-12T00:00:00+00:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "@search.action": "upload", - "hotelId": "6", - "description": "Surprisingly expensive. Model suites have an ocean-view." - }, - { - "@search.action": "upload", - "hotelId": "7", - "hotelName": "Modern Stay", - "description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "@search.action": "upload", - "hotelId": "8", - "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "@search.action": "upload", - "hotelId": "9", - "hotelName": "Secret Point Motel", - "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "category": "Boutique", - "tags": [ - "pool", - "air conditioning", - "concierge" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1970-01-18T00:00:00-05:00", - "rating": 4, - "location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "address": { - "streetAddress": "677 5th Ave", - "city": "New York", - "stateProvince": "NY", - "country": "USA", - "postalCode": "10022" - }, - "rooms": [ - { - "description": "Budget Room, 1 Queen Bed (Cityside)", - "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", - "type": "Budget Room", - "baseRate": 9.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd" - ] - }, - { - "description": "Budget Room, 1 King Bed (Mountain View)", - "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", - "type": "Budget Room", - "baseRate": 8.09, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "@search.action": "upload", - "hotelId": "10", - "hotelName": "Countryside Hotel", - "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", - "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", - "category": "Budget", - "tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "parkingIncluded": false, - "smokingAllowed": true, - "lastRenovationDate": "1999-09-06T00:00:00+00:00", - "rating": 3, - "location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.90416 - ] - }, - "address": { - "streetAddress": "6910 Fayetteville Rd", - "city": "Durham", - "stateProvince": "NC", - "country": "USA", - "postalCode": "27713" - }, - "rooms": [ - { - "description": "Suite, 1 King Bed (Amenities)", - "descriptionFr": "Suite, 1 très grand lit (Services)", - "type": "Suite", - "baseRate": 2.44, - "bedOptions": "1 King Bed", - "sleepsCount": 2, - "smokingAllowed": true, - "tags": [ - "coffee maker" - ] - }, - { - "description": "Budget Room, 1 Queen Bed (Amenities)", - "descriptionFr": "Chambre Économique, 1 grand lit (Services)", - "type": "Budget Room", - "baseRate": 7.69, - "bedOptions": "1 Queen Bed", - "sleepsCount": 2, - "smokingAllowed": false, - "tags": [ - "coffee maker" - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/README.md b/sdk/search/azure-search-documents/tests/perfstress_tests/README.md deleted file mode 100644 index 164216faf843..000000000000 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# Search Performance Tests - -In order to run the performance tests, the `devtools_testutils` package must be installed. This is done as part of the `dev_requirements`. -Start be creating a new virtual environment for your perf tests. This will need to be a Python 3 environment, preferably >=3.8. - -### Setup for test resources - -These tests will run against a pre-configured search service. See [here](https://learn.microsoft.com/azure/search/search-indexer-tutorial) about how to configure the service and import data. The following environment variable will need to be set for the tests to access the live resources: -``` -AZURE_SEARCH_API_KEY= -AZURE_SEARCH_SERVICE_ENDPOINT= -AZURE_SEARCH_INDEX_NAME= -``` - -### Setup for perf test runs - -```cmd -(env) ~/search/azure-search-documents> pip install -r dev_requirements.txt -(env) ~/search/azure-search-documents> pip install -e . -``` - -## Test commands - -When `devtools_testutils` is installed, you will have access to the `perfstress` command line tool, which will scan the current module for runable perf tests. Only a specific test can be run at a time (i.e. there is no "run all" feature). - -```cmd -(env) ~/search/azure-search-documents> cd tests -(env) ~/search/azure-search-documents/tests> perfstress -``` -Using the `perfstress` command alone will list the available perf tests found. - -### Common perf command line options -These options are available for all perf tests: -- `--duration=10` Number of seconds to run as many operations (the "run" function) as possible. Default is 10. -- `--iterations=1` Number of test iterations to run. Default is 1. -- `--parallel=1` Number of tests to run in parallel. Default is 1. -- `--warm-up=5` Number of seconds to spend warming up the connection before measuring begins. Default is 5. -- `--sync` Whether to run the tests in sync or async. Default is False (async). This flag must be used for Storage legacy tests, which do not support async. -- `--no-cleanup` Whether to keep newly created resources after test run. Default is False (resources will be deleted). -- `--num-documents` The number of results expect to be returned. - -## Example command -```cmd -(env) ~/search/azure-search-documents/tests> perfstress SearchDocumentsTest -(env) ~/search/azure-search-documents/tests> perfstress AutoCompleteTest -(env) ~/search/azure-search-documents/tests> perfstress SuggestTest -``` diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/__init__.py b/sdk/search/azure-search-documents/tests/perfstress_tests/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py b/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py deleted file mode 100644 index ccd2a6a595f6..000000000000 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py +++ /dev/null @@ -1,55 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import os -from devtools_testutils.perfstress_tests import PerfStressTest - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient as SyncClient -from azure.search.documents.aio import SearchClient as AsyncClient - - -class AutoCompleteTest(PerfStressTest): - def __init__(self, arguments): - super().__init__(arguments) - api_key = self.get_from_env("AZURE_SEARCH_API_KEY") - service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") - index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") - key = os.getenv("AZURE_SEARCH_API_KEY") - self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) - self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) - - async def close(self): - await self.async_service_client.close() - await super().close() - - @staticmethod - def add_arguments(parser): - super(AutoCompleteTest, AutoCompleteTest).add_arguments(parser) - parser.add_argument( - "--num-documents", - nargs="?", - type=int, - help="The number of results expect to be returned.", - default=-1, - ) - - def run_sync(self): - if self.args.num_documents == -1: - results = len(self.service_client.autocomplete(search_text="mot", suggester_name="sg")) - else: - results = len( - self.service_client.autocomplete(search_text="mot", suggester_name="sg", top=self.args.num_documents) - ) - - async def run_async(self): - if self.args.num_documents == -1: - results = len(await self.async_service_client.autocomplete(search_text="mot", suggester_name="sg")) - else: - results = len( - await self.async_service_client.autocomplete( - search_text="mot", suggester_name="sg", top=self.args.num_documents - ) - ) diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py b/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py deleted file mode 100644 index 19fc00efec37..000000000000 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py +++ /dev/null @@ -1,56 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import os - -from devtools_testutils.perfstress_tests import PerfStressTest - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient as SyncClient -from azure.search.documents.aio import SearchClient as AsyncClient - - -class SearchDocumentsTest(PerfStressTest): - def __init__(self, arguments): - super().__init__(arguments) - api_key = self.get_from_env("AZURE_SEARCH_API_KEY") - service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") - index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") - key = os.getenv("AZURE_SEARCH_API_KEY") - self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) - self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) - - @staticmethod - def add_arguments(parser): - super(SearchDocumentsTest, SearchDocumentsTest).add_arguments(parser) - parser.add_argument( - "--num-documents", - nargs="?", - type=int, - help="The number of results expect to be returned.", - default=-1, - ) - - async def global_setup(self): - await super().global_setup() - - async def close(self): - await self.async_service_client.close() - await super().close() - - def run_sync(self): - if self.args.num_documents == -1: - results = len(self.service_client.search(search_text="luxury")) - else: - results = len(self.service_client.search(search_text="luxury", top=self.args.num_documents)) - - async def run_async(self): - if self.args.num_documents == -1: - results = await self.async_service_client.search(search_text="luxury") - else: - results = await self.async_service_client.search(search_text="luxury", top=self.args.num_documents) - count = 0 - async for result in results: - count += count diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py b/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py deleted file mode 100644 index d906ba271ef8..000000000000 --- a/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py +++ /dev/null @@ -1,55 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import os -from devtools_testutils.perfstress_tests import PerfStressTest - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient as SyncClient -from azure.search.documents.aio import SearchClient as AsyncClient - - -class SuggestTest(PerfStressTest): - def __init__(self, arguments): - super().__init__(arguments) - api_key = self.get_from_env("AZURE_SEARCH_API_KEY") - service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") - index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") - key = os.getenv("AZURE_SEARCH_API_KEY") - self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) - self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) - - async def close(self): - await self.async_service_client.close() - await super().close() - - @staticmethod - def add_arguments(parser): - super(SuggestTest, SuggestTest).add_arguments(parser) - parser.add_argument( - "--num-documents", - nargs="?", - type=int, - help="The number of results expect to be returned.", - default=-1, - ) - - def run_sync(self): - if self.args.num_documents == -1: - results = len(self.service_client.suggest(search_text="mot", suggester_name="sg")) - else: - results = len( - self.service_client.suggest(search_text="mot", suggester_name="sg", top=self.args.num_documents) - ) - - async def run_async(self): - if self.args.num_documents == -1: - results = len(await self.async_service_client.suggest(search_text="mot", suggester_name="sg")) - else: - results = len( - await self.async_service_client.suggest( - search_text="mot", suggester_name="sg", top=self.args.num_documents - ) - ) diff --git a/sdk/search/azure-search-documents/tests/search_service_preparer.py b/sdk/search/azure-search-documents/tests/search_service_preparer.py deleted file mode 100644 index d4de15e3b660..000000000000 --- a/sdk/search/azure-search-documents/tests/search_service_preparer.py +++ /dev/null @@ -1,158 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import functools -from os import environ -from os.path import dirname, realpath, join - -import inspect -import json -import requests - -from devtools_testutils import AzureTestError, EnvironmentVariableLoader, get_credential - -from azure.core.exceptions import HttpResponseError - -SERVICE_URL_FMT = "https://{}.{}/indexes?api-version=2023-11-01" -TIME_TO_SLEEP = 3 -SEARCH_ENDPOINT_SUFFIX = environ.get("SEARCH_ENDPOINT_SUFFIX", "search.windows.net") - -SearchEnvVarPreparer = functools.partial( - EnvironmentVariableLoader, - "search", - search_service_endpoint="https://fakesearchendpoint.search.windows.net", - search_service_name="fakesearchendpoint", - search_storage_connection_string="DefaultEndpointsProtocol=https;AccountName=fakestoragecs;AccountKey=FAKE;EndpointSuffix=core.windows.net", - search_storage_container_name="fakestoragecontainer", -) - - -def _load_schema(filename): - if not filename: - return None - cwd = dirname(realpath(__file__)) - return open(join(cwd, filename)).read() - - -def _load_batch(filename): - if not filename: - return None - cwd = dirname(realpath(__file__)) - try: - return json.load(open(join(cwd, filename))) - except UnicodeDecodeError: - return json.load(open(join(cwd, filename), encoding="utf-8")) - - -def _clean_up_indexes(endpoint, cred): - from azure.search.documents.indexes import SearchIndexClient - - client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) - - # wipe the synonym maps which seem to survive the index - for map in client.get_synonym_maps(): - client.delete_synonym_map(map.name) - # wipe out any existing aliases - for alias in client.list_aliases(): - client.delete_alias(alias) - - # wipe any existing indexes - for index in client.list_indexes(): - client.delete_index(index) - - -def _clean_up_indexers(endpoint, cred): - from azure.search.documents.indexes import SearchIndexerClient - - client = SearchIndexerClient(endpoint, cred, retry_backoff_factor=60) - for indexer in client.get_indexers(): - client.delete_indexer(indexer) - for datasource in client.get_data_source_connection_names(): - client.delete_data_source_connection(datasource) - try: - for skillset in client.get_skillset_names(): - client.delete_skillset(skillset) - except HttpResponseError as ex: - if "skillset related operations are not enabled in this region" in ex.message.lower(): - pass - else: - raise - - -def _set_up_index(service_name, endpoint, cred, schema, index_batch): - from azure.search.documents import SearchClient - from azure.search.documents.indexes.models import SearchIndex - from azure.search.documents._generated.models import IndexBatch - from azure.search.documents.indexes import SearchIndexClient - - schema = _load_schema(schema) - index_batch = _load_batch(index_batch) - if schema: - index_json = json.loads(schema) - index_name = index_json["name"] - index = SearchIndex.from_dict(index_json) - index_client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) - index_create = index_client.create_index(index) - - # optionally load data into the index - if index_batch and schema: - batch = IndexBatch.deserialize(index_batch) - client = SearchClient(endpoint, index_name, cred) - results = client.index_documents(batch) - if not all(result.succeeded for result in results): - raise AzureTestError("Document upload to search index failed") - - # Indexing is asynchronous, so if you get a 200 from the REST API, that only means that the documents are - # persisted, not that they're searchable yet. The only way to check for searchability is to run queries, - # and even then things are eventually consistent due to replication. In the Track 1 SDK tests, we "solved" - # this by using a constant delay between indexing and querying. - import time - - time.sleep(TIME_TO_SLEEP) - - -def _trim_kwargs_from_test_function(fn, kwargs): - # the next function is the actual test function. the kwargs need to be trimmed so - # that parameters which are not required will not be passed to it. - if not getattr(fn, "__is_preparer", False): - try: - args, _, kw, _, _, _, _ = inspect.getfullargspec(fn) - except AttributeError: - args, _, kw, _ = inspect.getargspec(fn) # pylint: disable=deprecated-method - if kw is None: - args = set(args) - for key in [k for k in kwargs if k not in args]: - del kwargs[key] - - -def search_decorator(*, schema, index_batch): - def decorator(func): - def wrapper(*args, **kwargs): - # set up hotels search index - test = args[0] - endpoint = kwargs.get("search_service_endpoint") - service_name = kwargs.get("search_service_name") - if test.is_live: - cred = get_credential() - _clean_up_indexes(endpoint, cred) - _set_up_index(service_name, endpoint, cred, schema, index_batch) - _clean_up_indexers(endpoint, cred) - index_name = json.loads(_load_schema(schema))["name"] if schema else None - index_batch_data = _load_batch(index_batch) if index_batch else None - - # ensure that the names in the test signatures are in the - # bag of kwargs - kwargs["endpoint"] = endpoint - kwargs["index_name"] = index_name - kwargs["index_batch"] = index_batch_data - - trimmed_kwargs = {k: v for k, v in kwargs.items()} - _trim_kwargs_from_test_function(func, trimmed_kwargs) - - return func(*args, **trimmed_kwargs) - - return wrapper - - return decorator diff --git a/sdk/search/azure-search-documents/tests/test_buffered_sender.py b/sdk/search/azure-search-documents/tests/test_buffered_sender.py deleted file mode 100644 index 5af0b3d5efbf..000000000000 --- a/sdk/search/azure-search-documents/tests/test_buffered_sender.py +++ /dev/null @@ -1,154 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -from unittest import mock -import pytest -from azure.search.documents import ( - SearchIndexingBufferedSender, -) -from azure.core.credentials import AzureKeyCredential -from azure.core.exceptions import HttpResponseError, ServiceResponseTimeoutError -from azure.search.documents.models import IndexingResult - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - - -class TestSearchBatchingClient: - def test_search_indexing_buffered_sender_kwargs(self): - with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, window=100) as client: - assert client._batch_action_count == 512 - assert client._max_retries_per_action == 3 - assert client._auto_flush_interval == 60 - assert client._auto_flush - - def test_batch_queue(self): - with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: - assert client._index_documents_batch - client.upload_documents(["upload1"]) - client.delete_documents(["delete1", "delete2"]) - client.merge_documents(["merge1", "merge2", "merge3"]) - client.merge_or_upload_documents(["merge_or_upload1"]) - assert len(client.actions) == 7 - actions = client._index_documents_batch.dequeue_actions() - assert len(client.actions) == 0 - client._index_documents_batch.enqueue_actions(actions) - assert len(client.actions) == 7 - actions = client._index_documents_batch.dequeue_actions() - assert len(client.actions) == 0 - for action in actions: - client._index_documents_batch.enqueue_actions(action) - assert len(client.actions) == 7 - - @mock.patch( - "azure.search.documents._search_indexing_buffered_sender.SearchIndexingBufferedSender._process_if_needed" - ) - def test_process_if_needed(self, mock_process_if_needed): - with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL) as client: - client.upload_documents(["upload1"]) - client.delete_documents(["delete1", "delete2"]) - assert mock_process_if_needed.called - - @mock.patch("azure.search.documents._search_indexing_buffered_sender.SearchIndexingBufferedSender._cleanup") - def test_context_manager(self, mock_cleanup): - with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: - client.upload_documents(["upload1"]) - client.delete_documents(["delete1", "delete2"]) - assert mock_cleanup.called - - def test_flush(self): - DOCUMENT = { - "category": "Hotel", - "hotelId": "1000", - "rating": 4.0, - "rooms": [], - "hotelName": "Azure Inn", - } - with mock.patch.object( - SearchIndexingBufferedSender, - "_index_documents_actions", - side_effect=HttpResponseError("Error"), - ): - with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: - client._index_key = "hotelId" - client.upload_documents([DOCUMENT]) - client.flush() - assert len(client.actions) == 0 - - def test_callback_new(self): - on_new = mock.Mock() - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False, on_new=on_new - ) as client: - client.upload_documents(["upload1"]) - assert on_new.called - - def test_callback_error(self): - def mock_fail_index_documents(actions, timeout=86400): - if len(actions) > 0: - result = IndexingResult() - result.key = actions[0].additional_properties.get("id") - result.status_code = 400 - result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 - return [result] - - on_error = mock.Mock() - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error - ) as client: - client._index_documents_actions = mock_fail_index_documents - client._index_key = "id" - client.upload_documents({"id": 0}) - client.flush() - assert on_error.called - - def test_callback_error_on_timeout(self): - def mock_fail_index_documents(actions, timeout=86400): - import time - - if len(actions) > 0: - result = IndexingResult() - result.key = actions[0].additional_properties.get("id") - result.status_code = 400 - result.succeeded = False - self.uploaded = self.uploaded + len(actions) - 1 - time.sleep(1) - return [result] - - on_error = mock.Mock() - with SearchIndexingBufferedSender( - "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error - ) as client: - client._index_documents_actions = mock_fail_index_documents - client._index_key = "id" - client.upload_documents([{"id": 0}, {"id": 1}]) - with pytest.raises(ServiceResponseTimeoutError): - client.flush(timeout=-1) - assert on_error.call_count == 2 - - def test_callback_progress(self): - def mock_successful_index_documents(actions, timeout=86400): - if len(actions) > 0: - result = IndexingResult() - result.key = actions[0].additional_properties.get("id") - result.status_code = 200 - result.succeeded = True - return [result] - - on_progress = mock.Mock() - on_remove = mock.Mock() - with SearchIndexingBufferedSender( - "endpoint", - "index name", - CREDENTIAL, - auto_flush=False, - on_progress=on_progress, - on_remove=on_remove, - ) as client: - client._index_documents_actions = mock_successful_index_documents - client._index_key = "id" - client.upload_documents({"id": 0}) - client.flush() - assert on_progress.called - assert on_remove.called diff --git a/sdk/search/azure-search-documents/tests/test_index_documents_batch.py b/sdk/search/azure-search-documents/tests/test_index_documents_batch.py deleted file mode 100644 index c9d8c488d1ce..000000000000 --- a/sdk/search/azure-search-documents/tests/test_index_documents_batch.py +++ /dev/null @@ -1,69 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import pytest - -from azure.search.documents.models import IndexAction - -from azure.search.documents import IndexDocumentsBatch - -METHOD_NAMES = [ - "add_upload_actions", - "add_delete_actions", - "add_merge_actions", - "add_merge_or_upload_actions", -] - -METHOD_MAP = dict(zip(METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"])) - - -class TestIndexDocumentsBatch: - def test_init(self): - batch = IndexDocumentsBatch() - assert batch.actions == [] - - def test_repr(self): - batch = IndexDocumentsBatch() - assert repr(batch) == "" - - batch._actions = [1, 2, 3] - assert repr(batch) == "" - - # a strict length test here would require constructing an actions list - # with a length of ~10**24, so settle for this simple sanity check on - # an extreme case. - batch_actions = list(range(2000)) - assert len(repr(batch)) <= 1024 - - def test_actions_returns_list_copy(self): - batch = IndexDocumentsBatch() - batch.actions.extend([1, 2, 3]) - assert type(batch.actions) is list - assert batch.actions == [] - assert batch.actions is not batch._actions - - @pytest.mark.parametrize("method_name", METHOD_NAMES) - def test_add_method(self, method_name): - batch = IndexDocumentsBatch() - - method = getattr(batch, method_name) - - method("doc1") - assert len(batch.actions) == 1 - - method("doc2", "doc3") - assert len(batch.actions) == 3 - - method(["doc4", "doc5"]) - assert len(batch.actions) == 5 - - method(("doc6", "doc7")) - assert len(batch.actions) == 7 - - assert all(action.action_type == METHOD_MAP[method_name] for action in batch.actions) - assert all(type(action) == IndexAction for action in batch.actions) - - expected = ["doc{}".format(i) for i in range(1, 8)] - assert [action.additional_properties for action in batch.actions] == expected diff --git a/sdk/search/azure-search-documents/tests/test_index_field_helpers.py b/sdk/search/azure-search-documents/tests/test_index_field_helpers.py deleted file mode 100644 index 8e33f161af67..000000000000 --- a/sdk/search/azure-search-documents/tests/test_index_field_helpers.py +++ /dev/null @@ -1,90 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.search.documents.indexes.models import ( - ComplexField, - SearchableField, - SimpleField, - SearchFieldDataType, -) - - -def test_edm_contents(): - assert SearchFieldDataType.String == "Edm.String" - assert SearchFieldDataType.Int32 == "Edm.Int32" - assert SearchFieldDataType.Int64 == "Edm.Int64" - assert SearchFieldDataType.Double == "Edm.Double" - assert SearchFieldDataType.Boolean == "Edm.Boolean" - assert SearchFieldDataType.DateTimeOffset == "Edm.DateTimeOffset" - assert SearchFieldDataType.GeographyPoint == "Edm.GeographyPoint" - assert SearchFieldDataType.ComplexType == "Edm.ComplexType" - assert SearchFieldDataType.Collection("foo") == "Collection(foo)" - - -class TestComplexField: - def test_single(self): - fld = ComplexField(name="foo", fields=[]) - assert fld.name == "foo" - assert fld.type == SearchFieldDataType.ComplexType - - assert fld.sortable is None - assert fld.facetable is None - assert fld.searchable is None - assert fld.filterable is None - assert fld.analyzer_name is None - assert fld.search_analyzer_name is None - assert fld.index_analyzer_name is None - assert fld.synonym_map_names is None - - generated_field = fld._to_generated() - assert generated_field.retrievable is None - - def test_collection(self): - fld = ComplexField(name="foo", fields=[], collection=True) - assert fld.name == "foo" - assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.ComplexType) - - assert fld.sortable is None - assert fld.facetable is None - assert fld.searchable is None - assert fld.filterable is None - assert fld.analyzer_name is None - assert fld.search_analyzer_name is None - assert fld.index_analyzer_name is None - assert fld.synonym_map_names is None - - -class TestSimplexField: - def test_defaults(self): - fld = SimpleField(name="foo", type=SearchFieldDataType.Double) - assert fld.name == "foo" - assert fld.type == SearchFieldDataType.Double - assert fld.hidden == False - assert fld.sortable == False - assert fld.facetable == False - assert fld.searchable == False - assert fld.filterable == False - - assert fld.analyzer_name is None - assert fld.search_analyzer_name is None - assert fld.index_analyzer_name is None - assert fld.synonym_map_names is None - - -class TestSearchableField: - def test_defaults(self): - fld = SearchableField(name="foo", collection=True) - assert fld.name == "foo" - assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.String) - assert fld.hidden == False - assert fld.sortable == False - assert fld.facetable == False - assert fld.searchable == True - assert fld.filterable == False - - assert fld.analyzer_name is None - assert fld.search_analyzer_name is None - assert fld.index_analyzer_name is None - assert fld.synonym_map_names is None diff --git a/sdk/search/azure-search-documents/tests/test_models.py b/sdk/search/azure-search-documents/tests/test_models.py deleted file mode 100644 index 299ee69091a6..000000000000 --- a/sdk/search/azure-search-documents/tests/test_models.py +++ /dev/null @@ -1,45 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.search.documents.indexes.models import ( - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, - SearchResourceEncryptionKey, - SearchIndexerSkillset, - ShaperSkill, - SearchIndexer, -) - - -def test_encryption_key_serialization(): - from azure.search.documents.indexes._generated.models import ( - SearchResourceEncryptionKey as SearchResourceEncryptionKeyGen, - ) - - container = SearchIndexerDataContainer(name="container_name") - encryption_key = SearchResourceEncryptionKey( - key_name="key", - key_version="key_version", - vault_uri="vault_uri", - application_id="application_id", - ) - data_source_connection = SearchIndexerDataSourceConnection( - name="datasource-name", - type="azureblob", - connection_string="connection_string", - container=container, - encryption_key=encryption_key, - ) - packed_data_source = data_source_connection._to_generated() - assert isinstance(packed_data_source.encryption_key, SearchResourceEncryptionKeyGen) - - search_indexer = SearchIndexer( - name="indexer-name", - data_source_name="datasource-name", - target_index_name="target-index-name", - encryption_key=encryption_key, - ) - packed_search_indexer = search_indexer._to_generated() - assert isinstance(packed_search_indexer.encryption_key, SearchResourceEncryptionKeyGen) diff --git a/sdk/search/azure-search-documents/tests/test_queries.py b/sdk/search/azure-search-documents/tests/test_queries.py deleted file mode 100644 index dacac2c74ad1..000000000000 --- a/sdk/search/azure-search-documents/tests/test_queries.py +++ /dev/null @@ -1,165 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import pytest -from unittest import mock - -from azure.search.documents._generated.models import ( - AutocompleteRequest, - SearchRequest, - SuggestRequest, -) - -from azure.search.documents._queries import AutocompleteQuery, SuggestQuery, SearchQuery - - -class TestAutocompleteQuery: - def test_init(self): - query = AutocompleteQuery(search_text="text", suggester_name="sg") - assert type(query.request) is AutocompleteRequest - assert query.request.filter is None - - @mock.patch("azure.search.documents._queries.AutocompleteQuery._request_type") - def test_kwargs_forwarded(self, mock_request): - mock_request.return_value = None - AutocompleteQuery(foo=10, bar=20) - assert mock_request.called - assert mock_request.call_args[0] == () - assert mock_request.call_args[1] == {"foo": 10, "bar": 20} - - def test_repr(self): - query = AutocompleteQuery(search_text="foo bar", suggester_name="sg") - assert repr(query) == "" - - query = AutocompleteQuery(search_text="aaaaabbbbb" * 200, suggester_name="sg") - assert len(repr(query)) == 1024 - - def test_filter(self): - query = AutocompleteQuery(search_text="text", suggester_name="sg") - assert query.request.filter is None - query.filter("expr0") - assert query.request.filter == "expr0" - - query = AutocompleteQuery(search_text="text", suggester_name="sg", filter="expr1") - assert query.request.filter == "expr1" - query.filter("expr2") - assert query.request.filter == "expr2" - - -class TestSearchQuery: - def test_init(self): - query = SearchQuery() - assert type(query.request) is SearchRequest - assert query.request.filter is None - assert query.request.order_by is None - assert query.request.select is None - - @mock.patch("azure.search.documents._queries.SearchQuery._request_type") - def test_kwargs_forwarded(self, mock_request): - mock_request.return_value = None - SearchQuery(foo=10, bar=20) - assert mock_request.called - assert mock_request.call_args[0] == () - assert mock_request.call_args[1] == {"foo": 10, "bar": 20} - - def test_repr(self): - query = SearchQuery() - assert repr(query) == "" - - query = SearchQuery(search_text="foo bar", suggester_name="sg") - assert repr(query) == "" - - query = SearchQuery(search_text="aaaaabbbbb" * 200) - assert len(repr(query)) == 1024 - - def test_filter(self): - query = SearchQuery() - assert query.request.filter is None - query.filter("expr0") - assert query.request.filter == "expr0" - - query = SearchQuery(filter="expr0") - assert query.request.filter == "expr0" - query.filter("expr1") - assert query.request.filter == "expr1" - - def test_order_by(self): - query = SearchQuery() - assert query.request.order_by is None - query.order_by("f0") - assert query.request.order_by == "f0" - query.order_by("f1,f2") - assert query.request.order_by == "f1,f2" - query.order_by("f3", "f4") - assert query.request.order_by == "f3,f4" - - query = SearchQuery(order_by="f0") - assert query.request.order_by == "f0" - query.order_by("f1,f2") - assert query.request.order_by == "f1,f2" - query.order_by("f3", "f4") - assert query.request.order_by == "f3,f4" - - with pytest.raises(ValueError) as e: - query.order_by() - assert str(e) == "At least one field must be provided" - - def test_select(self): - query = SearchQuery() - assert query.request.select is None - query.select("f0") - assert query.request.select == "f0" - query.select("f1,f2") - assert query.request.select == "f1,f2" - query.select("f3", "f4") - assert query.request.select == "f3,f4" - - query = SearchQuery(select="f0") - assert query.request.select == "f0" - query.select("f1,f2") - assert query.request.select == "f1,f2" - query.select("f3", "f4") - assert query.request.select == "f3,f4" - - str = ["f1", "f2"] - query.select(str) - assert query.request.select == "f1,f2" - - with pytest.raises(ValueError) as e: - query.select() - assert str(e) == "At least one field must be provided" - - -class TestSuggestQuery: - def test_init(self): - query = SuggestQuery(search_text="text", suggester_name="sg") - assert type(query.request) is SuggestRequest - assert query.request.filter is None - - @mock.patch("azure.search.documents._queries.SuggestQuery._request_type") - def test_kwargs_forwarded(self, mock_request): - mock_request.return_value = None - SuggestQuery(foo=10, bar=20) - assert mock_request.called - assert mock_request.call_args[0] == () - assert mock_request.call_args[1] == {"foo": 10, "bar": 20} - - def test_repr(self): - query = SuggestQuery(search_text="foo bar", suggester_name="sg") - assert repr(query) == "" - - query = SuggestQuery(search_text="aaaaabbbbb" * 200, suggester_name="sg") - assert len(repr(query)) == 1024 - - def test_filter(self): - query = SuggestQuery(search_text="text", suggester_name="sg") - assert query.request.filter is None - query.filter("expr0") - assert query.request.filter == "expr0" - - query = SuggestQuery(search_text="text", suggester_name="sg", filter="expr1") - assert query.request.filter == "expr1" - query.filter("expr2") - assert query.request.filter == "expr2" diff --git a/sdk/search/azure-search-documents/tests/test_regex_flags.py b/sdk/search/azure-search-documents/tests/test_regex_flags.py deleted file mode 100644 index cee471b5d1df..000000000000 --- a/sdk/search/azure-search-documents/tests/test_regex_flags.py +++ /dev/null @@ -1,102 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.search.documents.indexes.models import ( - SearchIndex, - RegexFlags, - PatternAnalyzer, - PatternTokenizer, -) -from azure.search.documents.indexes._generated.models import ( - PatternAnalyzer as _PatternAnalyzer, - PatternTokenizer as _PatternTokenizer, -) - - -def test_unpack_search_index(): - pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags="CANON_EQ") - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags="CANON_EQ") - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) - result = SearchIndex._from_generated(index) - assert isinstance(result.analyzers[0], PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, list) - assert result.analyzers[0].flags[0] == "CANON_EQ" - assert isinstance(result.tokenizers[0], PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, list) - assert result.tokenizers[0].flags[0] == "CANON_EQ" - - -def test_multi_unpack_search_index(): - pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags="CANON_EQ|MULTILINE") - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags="CANON_EQ|MULTILINE") - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) - result = SearchIndex._from_generated(index) - assert isinstance(result.analyzers[0], PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, list) - assert result.analyzers[0].flags[0] == "CANON_EQ" - assert result.analyzers[0].flags[1] == "MULTILINE" - assert isinstance(result.tokenizers[0], PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, list) - assert result.tokenizers[0].flags[0] == "CANON_EQ" - assert result.tokenizers[0].flags[1] == "MULTILINE" - - -def test_unpack_search_index_enum(): - pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags=RegexFlags.canon_eq) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags=RegexFlags.canon_eq) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) - result = SearchIndex._from_generated(index) - assert isinstance(result.analyzers[0], PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, list) - assert result.analyzers[0].flags[0] == "CANON_EQ" - assert isinstance(result.tokenizers[0], PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, list) - assert result.tokenizers[0].flags[0] == "CANON_EQ" - - -def test_pack_search_index(): - pattern_analyzer = PatternAnalyzer(name="test_analyzer", flags=["CANON_EQ"]) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = PatternTokenizer(name="test_tokenizer", flags=["CANON_EQ"]) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) - result = index._to_generated() - assert isinstance(result.analyzers[0], _PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, str) - assert result.analyzers[0].flags == "CANON_EQ" - assert isinstance(result.tokenizers[0], _PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, str) - assert result.tokenizers[0].flags == "CANON_EQ" - - -def test_multi_pack_search_index(): - pattern_analyzer = PatternAnalyzer(name="test_analyzer", flags=["CANON_EQ", "MULTILINE"]) - analyzers = [] - analyzers.append(pattern_analyzer) - pattern_tokenizer = PatternTokenizer(name="test_analyzer", flags=["CANON_EQ", "MULTILINE"]) - tokenizers = [] - tokenizers.append(pattern_tokenizer) - index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) - result = index._to_generated() - assert isinstance(result.analyzers[0], _PatternAnalyzer) - assert isinstance(result.analyzers[0].flags, str) - assert result.analyzers[0].flags == "CANON_EQ|MULTILINE" - assert isinstance(result.tokenizers[0], _PatternTokenizer) - assert isinstance(result.tokenizers[0].flags, str) - assert result.tokenizers[0].flags == "CANON_EQ|MULTILINE" diff --git a/sdk/search/azure-search-documents/tests/test_search_client.py b/sdk/search/azure-search-documents/tests/test_search_client.py deleted file mode 100644 index f8833f55fdec..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_client.py +++ /dev/null @@ -1,323 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import pytest -from unittest import mock -from azure.core.paging import ItemPaged -from azure.core.credentials import AzureKeyCredential - -from azure.search.documents._generated.models import ( - SearchDocumentsResult, - SearchResult, -) -from azure.search.documents._search_client import SearchPageIterator - -from azure.search.documents import ( - IndexDocumentsBatch, - SearchClient, - RequestEntityTooLargeError, - ApiVersion, -) -from azure.search.documents._utils import odata, get_answer_query - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - -CRUD_METHOD_NAMES = [ - "upload_documents", - "delete_documents", - "merge_documents", - "merge_or_upload_documents", -] - -CRUD_METHOD_MAP = dict(zip(CRUD_METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"])) - - -class Test_odata: - def test_const(self): - assert odata("no escapes") == "no escapes" - - def test_numbers(self): - assert odata("foo eq {foo}", foo=10) == "foo eq 10" - - def test_string(self): - assert odata("foo eq {foo}", foo="a string") == "foo eq 'a string'" - - def test_mixed(self): - expected = "foo eq 'a string' and bar le 10" - out = odata("foo eq {foo} and bar le {bar}", foo="a string", bar=10) - assert out == expected - - def test_escape_single_quote(self): - assert odata("foo eq {foo}", foo="a '' str'ing") == "foo eq 'a '''' str''ing'" - - def test_prevent_double_quoting(self): - assert odata("foo eq '{foo}'", foo="a string") == "foo eq 'a string'" - - -class TestAnswerQuery: - def test_no_args(self): - assert get_answer_query() is None - - def test_query_answer(self): - assert get_answer_query("query") == "query" - - def test_query_answer_count(self): - assert get_answer_query("query", 5) == "query|count-5" - - def test_query_answer_threshold(self): - assert get_answer_query("query", query_answer_threshold=0.5) == "query|threshold-0.5" - - def test_query_answer_count_threshold(self): - assert get_answer_query("query", 5, 0.5) == "query|count-5,threshold-0.5" - - -class TestSearchClient: - def test_init(self): - client = SearchClient("endpoint", "index name", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=none", - } - - def test_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchClient("endpoint", "index name", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=none", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=none", - } - - def test_headers_merge(self): - credential = AzureKeyCredential(key="test_api_key") - client = SearchClient("endpoint", "index name", credential) - orig = {"foo": "bar"} - result = client._merge_client_headers(orig) - assert result is not orig - assert result == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=none", - "foo": "bar", - } - - def test_repr(self): - client = SearchClient("endpoint", "index name", CREDENTIAL) - assert repr(client) == "".format(repr("endpoint"), repr("index name")) - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.count") - def test_get_document_count(self, mock_count): - client = SearchClient("endpoint", "index name", CREDENTIAL) - client.get_document_count() - assert mock_count.called - assert mock_count.call_args[0] == () - assert len(mock_count.call_args[1]) == 1 - assert mock_count.call_args[1]["headers"] == client._headers - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.get") - def test_get_document(self, mock_get): - client = SearchClient("endpoint", "index name", CREDENTIAL) - client.get_document("some_key") - assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" - assert mock_get.call_args[1]["selected_fields"] == None - - mock_get.reset() - - client.get_document("some_key", selected_fields="foo") - assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" - assert mock_get.call_args[1]["selected_fields"] == "foo" - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post") - def test_search_query_argument(self, mock_search_post): - client = SearchClient("endpoint", "index name", CREDENTIAL) - result = client.search(search_text="search text") - assert isinstance(result, ItemPaged) - assert result._page_iterator_class is SearchPageIterator - search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] - mock_search_post.return_value = search_result - assert not mock_search_post.called - next(result) - assert mock_search_post.called - assert mock_search_post.call_args[0] == () - assert mock_search_post.call_args[1]["search_request"].search_text == "search text" - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.suggest_post") - def test_suggest_query_argument(self, mock_suggest_post): - client = SearchClient("endpoint", "index name", CREDENTIAL) - result = client.suggest(search_text="search text", suggester_name="sg") - assert mock_suggest_post.called - assert mock_suggest_post.call_args[0] == () - assert mock_suggest_post.call_args[1]["headers"] == client._headers - assert mock_suggest_post.call_args[1]["suggest_request"].search_text == "search text" - - def test_suggest_bad_argument(self): - client = SearchClient("endpoint", "index name", CREDENTIAL) - with pytest.raises(TypeError) as e: - client.suggest("bad_query") - assert str(e) == "Expected a SuggestQuery for 'query', but got {}".format(repr("bad_query")) - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post") - def test_get_count_reset_continuation_token(self, mock_search_post): - client = SearchClient("endpoint", "index name", CREDENTIAL) - result = client.search(search_text="search text") - assert isinstance(result, ItemPaged) - assert result._page_iterator_class is SearchPageIterator - search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] - mock_search_post.return_value = search_result - result.__next__() - result._first_page_iterator_instance.continuation_token = "fake token" - result.get_count() - assert not result._first_page_iterator_instance.continuation_token - - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.autocomplete_post" - ) - def test_autocomplete_query_argument(self, mock_autocomplete_post): - client = SearchClient("endpoint", "index name", CREDENTIAL) - result = client.autocomplete(search_text="search text", suggester_name="sg") - assert mock_autocomplete_post.called - assert mock_autocomplete_post.call_args[0] == () - assert mock_autocomplete_post.call_args[1]["headers"] == client._headers - assert mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text == "search text" - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.count") - def test_get_document_count_v2020_06_30(self, mock_count): - client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) - client.get_document_count() - assert mock_count.called - assert mock_count.call_args[0] == () - assert len(mock_count.call_args[1]) == 1 - assert mock_count.call_args[1]["headers"] == client._headers - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.get") - def test_get_document_v2020_06_30(self, mock_get): - client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) - client.get_document("some_key") - assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" - assert mock_get.call_args[1]["selected_fields"] == None - - mock_get.reset() - - client.get_document("some_key", selected_fields="foo") - assert mock_get.called - assert mock_get.call_args[0] == () - assert len(mock_get.call_args[1]) == 3 - assert mock_get.call_args[1]["headers"] == client._headers - assert mock_get.call_args[1]["key"] == "some_key" - assert mock_get.call_args[1]["selected_fields"] == "foo" - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post") - def test_search_query_argument_v2020_06_30(self, mock_search_post): - client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) - result = client.search(search_text="search text") - assert isinstance(result, ItemPaged) - assert result._page_iterator_class is SearchPageIterator - search_result = SearchDocumentsResult() - search_result.results = [SearchResult(additional_properties={"key": "val"})] - mock_search_post.return_value = search_result - assert not mock_search_post.called - next(result) - assert mock_search_post.called - assert mock_search_post.call_args[0] == () - assert mock_search_post.call_args[1]["search_request"].search_text == "search text" - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.suggest_post") - def test_suggest_query_argument_v2020_06_30(self, mock_suggest_post): - client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) - result = client.suggest(search_text="search text", suggester_name="sg") - assert mock_suggest_post.called - assert mock_suggest_post.call_args[0] == () - assert mock_suggest_post.call_args[1]["headers"] == client._headers - assert mock_suggest_post.call_args[1]["suggest_request"].search_text == "search text" - - @mock.patch( - "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.autocomplete_post" - ) - def test_autocomplete_query_argument_v2020_06_30(self, mock_autocomplete_post): - client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) - result = client.autocomplete(search_text="search text", suggester_name="sg") - assert mock_autocomplete_post.called - assert mock_autocomplete_post.call_args[0] == () - assert mock_autocomplete_post.call_args[1]["headers"] == client._headers - assert mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text == "search text" - - def test_autocomplete_bad_argument(self): - client = SearchClient("endpoint", "index name", CREDENTIAL) - with pytest.raises(TypeError) as e: - client.autocomplete("bad_query") - assert str(e) == "Expected a AutocompleteQuery for 'query', but got {}".format(repr("bad_query")) - - @pytest.mark.parametrize("arg", [[], ["doc1"], ["doc1", "doc2"]], ids=lambda x: str(len(x)) + " docs") - @pytest.mark.parametrize("method_name", CRUD_METHOD_NAMES) - def test_add_method(self, arg, method_name): - with mock.patch.object(SearchClient, "index_documents", return_value=None) as mock_index_documents: - client = SearchClient("endpoint", "index name", CREDENTIAL) - - method = getattr(client, method_name) - method(arg, extra="foo") - - assert mock_index_documents.called - assert len(mock_index_documents.call_args[0]) == 1 - batch = mock_index_documents.call_args[0][0] - assert isinstance(batch, IndexDocumentsBatch) - assert all(action.action_type == CRUD_METHOD_MAP[method_name] for action in batch.actions) - assert [action.additional_properties for action in batch.actions] == arg - assert mock_index_documents.call_args[1]["headers"] == client._headers - assert mock_index_documents.call_args[1]["extra"] == "foo" - - @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.index") - def test_index_documents(self, mock_index): - client = SearchClient("endpoint", "index name", CREDENTIAL) - - batch = IndexDocumentsBatch() - actions = batch.add_upload_actions("upload1") - assert len(actions) == 1 - for x in actions: - assert x.action_type == "upload" - actions = batch.add_delete_actions("delete1", "delete2") - assert len(actions) == 2 - for x in actions: - assert x.action_type == "delete" - actions = batch.add_merge_actions(["merge1", "merge2", "merge3"]) - for x in actions: - assert x.action_type == "merge" - actions = batch.add_merge_or_upload_actions("merge_or_upload1") - for x in actions: - assert x.action_type == "mergeOrUpload" - - client.index_documents(batch, extra="foo") - assert mock_index.called - assert mock_index.call_args[0] == () - assert mock_index.call_args[1]["headers"] == client._headers - assert mock_index.call_args[1]["extra"] == "foo" - - def test_request_too_large_error(self): - with mock.patch.object( - SearchClient, - "_index_documents_actions", - side_effect=RequestEntityTooLargeError("Error"), - ): - client = SearchClient("endpoint", "index name", CREDENTIAL) - batch = IndexDocumentsBatch() - batch.add_upload_actions("upload1") - with pytest.raises(RequestEntityTooLargeError): - client.index_documents(batch, extra="foo") diff --git a/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py b/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py deleted file mode 100644 index 5c1500615dee..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py +++ /dev/null @@ -1,41 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core.exceptions import HttpResponseError -from azure.search.documents import SearchClient -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClient(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_get_document_count(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) - assert client.get_document_count() == 10 - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_get_document(self, endpoint, index_name, index_batch): - client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) - for hotel_id in range(1, 11): - result = client.get_document(key=str(hotel_id)) - expected = index_batch["value"][hotel_id - 1] - assert result.get("hotelId") == expected.get("hotelId") - assert result.get("hotelName") == expected.get("hotelName") - assert result.get("description") == expected.get("description") - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_get_document_missing(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) - with pytest.raises(HttpResponseError): - client.get_document(key="1000") diff --git a/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py b/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py deleted file mode 100644 index 30d6f221bfd1..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py +++ /dev/null @@ -1,168 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -import time -from azure.core.exceptions import HttpResponseError -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchIndexingBufferedSender, SearchClient -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential -from search_service_preparer import SearchEnvVarPreparer, search_decorator - -TIME_TO_SLEEP = 3 - - -class TestSearchIndexingBufferedSender(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_search_client_index_buffered_sender(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) - batch_client = SearchIndexingBufferedSender(endpoint, index_name, get_credential(), retry_backoff_factor=60) - try: - doc_count = 10 - doc_count = self._test_upload_documents_new(client, batch_client, doc_count) - doc_count = self._test_upload_documents_existing(client, batch_client, doc_count) - doc_count = self._test_delete_documents_existing(client, batch_client, doc_count) - doc_count = self._test_delete_documents_missing(client, batch_client, doc_count) - doc_count = self._test_merge_documents_existing(client, batch_client, doc_count) - doc_count = self._test_merge_documents_missing(client, batch_client, doc_count) - doc_count = self._test_merge_or_upload_documents(client, batch_client, doc_count) - finally: - batch_client.close() - - def _test_upload_documents_new(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - docs = [ - {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - batch_client.upload_documents(docs) - doc_count += 2 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - for doc in docs: - result = client.get_document(key=doc["hotelId"]) - assert result["hotelId"] == doc["hotelId"] - assert result["hotelName"] == doc["hotelName"] - assert result["rating"] == doc["rating"] - assert result["rooms"] == doc["rooms"] - return doc_count - - def _test_upload_documents_existing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # add one new and one existing - docs = [ - {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - batch_client.upload_documents(docs) - doc_count += 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - return doc_count - - def _test_delete_documents_existing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - docs = [{"hotelId": "3"}, {"hotelId": "4"}] - batch_client.delete_documents(docs) - doc_count -= 2 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - client.get_document(key="3") - - with pytest.raises(HttpResponseError): - client.get_document(key="4") - return doc_count - - def _test_delete_documents_missing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # delete one existing and one missing - docs = [{"hotelId": "1003"}, {"hotelId": "2"}] - batch_client.delete_documents(docs) - doc_count -= 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - with pytest.raises(HttpResponseError): - client.get_document(key="1003") - with pytest.raises(HttpResponseError): - client.get_document(key="2") - return doc_count - - def _test_merge_documents_existing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] - batch_client.merge_documents(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - result = client.get_document(key="5") - assert result["rating"] == 1 - - result = client.get_document(key="6") - assert result["rating"] == 2 - return doc_count - - def _test_merge_documents_missing(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # merge to one existing and one missing document - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - batch_client.merge_documents(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - client.get_document(key="1003") - - result = client.get_document(key="1") - assert result["rating"] == 2 - return doc_count - - def _test_merge_or_upload_documents(self, client, batch_client, doc_count): - batch_client._batch_action_count = 2 - # merge to one existing and one missing - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - batch_client.merge_or_upload_documents(docs) - doc_count += 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - result = client.get_document(key="1003") - assert result["rating"] == 1 - - result = client.get_document(key="1") - assert result["rating"] == 2 - return doc_count diff --git a/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py b/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py deleted file mode 100644 index 52219a0819a0..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py +++ /dev/null @@ -1,167 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -import time -from azure.core.exceptions import HttpResponseError -from azure.search.documents import SearchClient -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential -from search_service_preparer import SearchEnvVarPreparer, search_decorator - -TIME_TO_SLEEP = 3 - - -class TestSearchClientIndexDocument(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_search_client_index_document(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) - doc_count = 10 - doc_count = self._test_upload_documents_new(client, doc_count) - doc_count = self._test_upload_documents_existing(client, doc_count) - doc_count = self._test_delete_documents_existing(client, doc_count) - doc_count = self._test_delete_documents_missing(client, doc_count) - doc_count = self._test_merge_documents_existing(client, doc_count) - doc_count = self._test_merge_documents_missing(client, doc_count) - doc_count = self._test_merge_or_upload_documents(client, doc_count) - - def _test_upload_documents_new(self, client, doc_count): - docs = [ - {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - results = client.upload_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {201} - doc_count += len(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - for doc in docs: - result = client.get_document(key=doc["hotelId"]) - assert result["hotelId"] == doc["hotelId"] - assert result["hotelName"] == doc["hotelName"] - assert result["rating"] == doc["rating"] - assert result["rooms"] == doc["rooms"] - return doc_count - - def _test_upload_documents_existing(self, client, doc_count): - # add one new and one existing - docs = [ - {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, - {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, - ] - results = client.upload_documents(docs) - assert len(results) == len(docs) - doc_count += 1 - assert set(x.status_code for x in results) == {200, 201} - return doc_count - - def _test_delete_documents_existing(self, client, doc_count): - docs = [{"hotelId": "3"}, {"hotelId": "4"}] - results = client.delete_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200} - doc_count -= len(docs) - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - client.get_document(key="3") - - with pytest.raises(HttpResponseError): - client.get_document(key="4") - return doc_count - - def _test_delete_documents_missing(self, client, doc_count): - # delete one existing and one missing - docs = [{"hotelId": "1003"}, {"hotelId": "2"}] - results = client.delete_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200} - doc_count -= 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - client.get_document(key="1003") - - with pytest.raises(HttpResponseError): - client.get_document(key="2") - return doc_count - - def _test_merge_documents_existing(self, client, doc_count): - docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] - results = client.merge_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200} - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - test = client.get_document_count() - assert client.get_document_count() == doc_count - - result = client.get_document(key="5") - assert result["rating"] == 1 - - result = client.get_document(key="6") - assert result["rating"] == 2 - return doc_count - - def _test_merge_documents_missing(self, client, doc_count): - # merge to one existing and one missing document - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - results = client.merge_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200, 404} - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - with pytest.raises(HttpResponseError): - client.get_document(key="1003") - - result = client.get_document(key="1") - assert result["rating"] == 2 - return doc_count - - def _test_merge_or_upload_documents(self, client, doc_count): - # merge to one existing and one missing - docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] - results = client.merge_or_upload_documents(docs) - assert len(results) == len(docs) - assert set(x.status_code for x in results) == {200, 201} - doc_count += 1 - - # There can be some lag before a document is searchable - if self.is_live: - time.sleep(TIME_TO_SLEEP) - - assert client.get_document_count() == doc_count - - result = client.get_document(key="1003") - assert result["rating"] == 1 - - result = client.get_document(key="1") - assert result["rating"] == 2 - return doc_count diff --git a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py deleted file mode 100644 index af86da2542c6..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py +++ /dev/null @@ -1,134 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.search.documents import SearchClient -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClient(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_search_client(self, endpoint, index_name): - client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) - self._test_get_search_simple(client) - self._test_get_search_simple_with_top(client) - self._test_get_search_filter(client) - self._test_get_search_filter_array(client) - self._test_get_search_counts(client) - self._test_get_search_coverage(client) - self._test_get_search_facets_none(client) - self._test_get_search_facets_result(client) - self._test_autocomplete(client) - self._test_suggest(client) - - def _test_get_search_simple(self, client): - results = list(client.search(search_text="hotel")) - assert len(results) == 7 - - results = list(client.search(search_text="motel")) - assert len(results) == 2 - - def _test_get_search_simple_with_top(self, client): - results = list(client.search(search_text="hotel", top=3)) - assert len(results) == 3 - - results = list(client.search(search_text="motel", top=3)) - assert len(results) == 2 - - def _test_get_search_filter(self, client): - select = ["hotelName", "category", "description"] - results = list( - client.search( - search_text="WiFi", - filter="category eq 'Budget'", - select=",".join(select), - order_by="hotelName desc", - ) - ) - assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) - expected = { - "category", - "hotelName", - "description", - "@search.score", - "@search.reranker_score", - "@search.highlights", - "@search.captions", - "@search.document_debug_info", - "@search.reranker_boosted_score", - } - assert all(set(x) == expected for x in results) - assert all(x["category"] == "Budget" for x in results) - - def _test_get_search_filter_array(self, client): - select = ["hotelName", "category", "description"] - results = list( - client.search( - search_text="WiFi", - filter="category eq 'Budget'", - select=select, - order_by="hotelName desc", - ) - ) - assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) - expected = { - "category", - "hotelName", - "description", - "@search.score", - "@search.reranker_score", - "@search.highlights", - "@search.captions", - "@search.document_debug_info", - "@search.reranker_boosted_score", - } - assert all(set(x) == expected for x in results) - assert all(x["category"] == "Budget" for x in results) - - def _test_get_search_counts(self, client): - results = client.search(search_text="hotel") - assert results.get_count() is None - - results = client.search(search_text="hotel", include_total_count=True) - assert results.get_count() == 7 - - def _test_get_search_coverage(self, client): - results = client.search(search_text="hotel") - assert results.get_coverage() is None - - results = client.search(search_text="hotel", minimum_coverage=50.0) - cov = results.get_coverage() - assert isinstance(cov, float) - assert cov >= 50.0 - - def _test_get_search_facets_none(self, client): - select = ("hotelName", "category", "description") - results = client.search(search_text="WiFi", select=",".join(select)) - assert results.get_facets() is None - - def _test_get_search_facets_result(self, client): - select = ("hotelName", "category", "description") - results = client.search(search_text="WiFi", facets=["category"], select=",".join(select)) - assert results.get_facets() == { - "category": [ - {"value": "Budget", "count": 4}, - {"value": "Luxury", "count": 1}, - ] - } - - def _test_autocomplete(self, client): - results = client.autocomplete(search_text="mot", suggester_name="sg") - assert results == [{"text": "motel", "query_plus_text": "motel"}] - - def _test_suggest(self, client): - results = client.suggest(search_text="mot", suggester_name="sg") - assert results == [ - {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, - {"hotelId": "9", "text": "Secret Point Motel"}, - ] diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client.py b/sdk/search/azure-search-documents/tests/test_search_index_client.py deleted file mode 100644 index 73973e36d3f1..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client.py +++ /dev/null @@ -1,130 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import pytest -from unittest import mock - -from azure.core.credentials import AzureKeyCredential -from azure.search.documents import SearchClient, ApiVersion -from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient -from azure.search.documents.indexes.models import ( - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, -) - -CREDENTIAL = AzureKeyCredential(key="test_api_key") - - -class TestSearchIndexClient: - def test_index_init(self): - client = SearchIndexClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_index_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential, retry_backoff_factor=60) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_get_search_client(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - - def test_get_search_client_inherit_api_version(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential, api_version=ApiVersion.V2020_06_30) - search_client = client.get_search_client("index") - assert isinstance(search_client, SearchClient) - assert search_client._api_version == ApiVersion.V2020_06_30 - - @mock.patch( - "azure.search.documents.indexes._generated.operations._search_service_client_operations._SearchServiceClientOperationsMixin.get_service_statistics" - ) - def test_get_service_statistics(self, mock_get_stats): - client = SearchIndexClient("endpoint", CREDENTIAL) - client.get_service_statistics() - assert mock_get_stats.called - assert mock_get_stats.call_args[0] == () - assert mock_get_stats.call_args[1] == {"headers": client._headers} - - @mock.patch( - "azure.search.documents.indexes._generated.operations._search_service_client_operations._SearchServiceClientOperationsMixin.get_service_statistics" - ) - def test_get_service_statistics_v2020_06_30(self, mock_get_stats): - client = SearchIndexClient("endpoint", CREDENTIAL, api_version=ApiVersion.V2020_06_30) - client.get_service_statistics() - assert mock_get_stats.called - assert mock_get_stats.call_args[0] == () - assert mock_get_stats.call_args[1] == {"headers": client._headers} - - def test_index_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexClient(12345, credential) - - -class TestSearchIndexerClient: - def test_indexer_init(self): - client = SearchIndexerClient("endpoint", CREDENTIAL) - assert client._headers == { - "api-key": "test_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_credential_roll(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._headers == { - "api-key": "old_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - credential.update("new_api_key") - assert client._headers == { - "api-key": "new_api_key", - "Accept": "application/json;odata.metadata=minimal", - } - - def test_indexer_endpoint_https(self): - credential = AzureKeyCredential(key="old_api_key") - client = SearchIndexerClient("endpoint", credential) - assert client._endpoint.startswith("https") - - client = SearchIndexerClient("https://endpoint", credential) - assert client._endpoint.startswith("https") - - with pytest.raises(ValueError): - client = SearchIndexerClient("http://endpoint", credential) - - with pytest.raises(ValueError): - client = SearchIndexerClient(12345, credential) - - def test_datasource_with_empty_connection_string(self): - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name="test", type="azureblob", connection_string="", container=container - ) - packed_data_source_connection = data_source_connection._to_generated() - assert packed_data_source_connection.credentials.connection_string == "" diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py deleted file mode 100644 index 0e91ad5774fa..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py +++ /dev/null @@ -1,108 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from unicodedata import name -import pytest - -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes import SearchIndexClient -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential -from azure.search.documents.indexes.models import ( - AnalyzeTextOptions, - CorsOptions, - SearchIndex, - ScoringProfile, - SimpleField, - SearchFieldDataType, - SearchAlias, -) - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClientAlias(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_alias(self, endpoint): - client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) - aliases = ["resort", "motel"] - index_name = next(client.list_index_names()) - self._test_list_aliases_empty(client) - self._test_create_alias(client, aliases[0], index_name) - - self._test_create_or_update_alias(client, aliases[1], index_name) - - # point an old alias to a new index - new_index_name = "hotel" - self._test_update_alias_to_new_index(client, aliases[1], new_index_name, index_name) - - self._test_get_alias(client, aliases) - - self._test_list_aliases(client, aliases) - self._test_delete_aliases(client) - - def _test_list_aliases_empty(self, client): - result = client.list_aliases() - with pytest.raises(StopIteration): - next(result) - - def _test_create_alias(self, client, alias_name, index_name): - alias = SearchAlias(name=alias_name, indexes=[index_name]) - result = client.create_alias(alias) - assert result.name == alias_name - assert set(result.indexes) == {index_name} - - def _test_create_or_update_alias(self, client, alias_name, index_name): - alias = SearchAlias(name=alias_name, indexes=[index_name]) - result = client.create_or_update_alias(alias) - assert result.name == alias_name - assert set(result.indexes) == {index_name} - - def _test_update_alias_to_new_index(self, client, alias_name, new_index, old_index): - self._create_index(client, new_index) - alias = SearchAlias(name=alias_name, indexes=[new_index]) - result = client.create_or_update_alias(alias) - - assert result.name == alias_name - assert result.indexes[0] != old_index - assert result.indexes[0] == new_index - - def _test_get_alias(self, client, aliases): - for alias in aliases: - result = client.get_alias(alias) - assert result - assert result.name == alias - - def _test_list_aliases(self, client, aliases): - result = {alias for alias in client.list_alias_names()} - assert result == set(aliases) - - def _test_delete_aliases(self, client): - aliases = client.list_aliases() - - for alias in aliases: - client.delete_alias(alias) - with pytest.raises(HttpResponseError): - result = client.get_alias(alias) - - def _create_index(self, client, index_name): - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=index_name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = client.create_index(index) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py deleted file mode 100644 index f60bf1cb39eb..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py +++ /dev/null @@ -1,136 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest - -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator -from azure.search.documents.indexes.models import ( - SearchIndexerDataSourceConnection, - SearchIndexerDataContainer, -) -from azure.search.documents.indexes import SearchIndexerClient - - -class TestSearchClientDataSources(AzureRecordedTestCase): - def _create_data_source_connection(self, cs, name): - container = SearchIndexerDataContainer(name="searchcontainer") - data_source_connection = SearchIndexerDataSourceConnection( - name=name, type="azureblob", connection_string=cs, container=container - ) - return data_source_connection - - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_data_source(self, endpoint, **kwargs): - storage_cs = kwargs.get("search_storage_connection_string") - client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) - self._test_create_datasource(client, storage_cs) - self._test_delete_datasource(client, storage_cs) - self._test_get_datasource(client, storage_cs) - self._test_list_datasources(client, storage_cs) - self._test_create_or_update_datasource(client, storage_cs) - self._test_create_or_update_datasource_if_unchanged(client, storage_cs) - self._test_delete_datasource_if_unchanged(client, storage_cs) - self._test_delete_datasource_string_if_unchanged(client, storage_cs) - - def _test_create_datasource(self, client, storage_cs): - ds_name = "create" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - result = client.create_data_source_connection(data_source_connection) - assert result.name == ds_name - assert result.type == "azureblob" - - def _test_delete_datasource(self, client, storage_cs): - ds_name = "delete" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - client.create_data_source_connection(data_source_connection) - expected_count = len(client.get_data_source_connections()) - 1 - client.delete_data_source_connection(ds_name) - assert len(client.get_data_source_connections()) == expected_count - - def _test_get_datasource(self, client, storage_cs): - ds_name = "get" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - client.create_data_source_connection(data_source_connection) - result = client.get_data_source_connection(ds_name) - assert result.name == ds_name - - def _test_list_datasources(self, client, storage_cs): - data_source_connection1 = self._create_data_source_connection(storage_cs, "list") - data_source_connection2 = self._create_data_source_connection(storage_cs, "list2") - client.create_data_source_connection(data_source_connection1) - client.create_data_source_connection(data_source_connection2) - result = client.get_data_source_connections() - assert isinstance(result, list) - assert set(x.name for x in result).intersection(set(["list", "list2"])) == set(["list", "list2"]) - - def _test_create_or_update_datasource(self, client, storage_cs): - ds_name = "cou" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - client.create_data_source_connection(data_source_connection) - expected_count = len(client.get_data_source_connections()) - data_source_connection.description = "updated" - client.create_or_update_data_source_connection(data_source_connection) - assert len(client.get_data_source_connections()) == expected_count - result = client.get_data_source_connection(ds_name) - assert result.name == ds_name - assert result.description == "updated" - - def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): - ds_name = "couunch" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - created = client.create_data_source_connection(data_source_connection) - etag = created.e_tag - - # Now update the data source connection - data_source_connection.description = "updated" - client.create_or_update_data_source_connection(data_source_connection) - - # prepare data source connection - data_source_connection.e_tag = etag # reset to the original data source connection - data_source_connection.description = "changed" - with pytest.raises(HttpResponseError): - client.create_or_update_data_source_connection( - data_source_connection, match_condition=MatchConditions.IfNotModified - ) - - def _test_delete_datasource_if_unchanged(self, client, storage_cs): - ds_name = "delunch" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - created = client.create_data_source_connection(data_source_connection) - etag = created.e_tag - - # Now update the data source connection - data_source_connection.description = "updated" - client.create_or_update_data_source_connection(data_source_connection) - - # prepare data source connection - data_source_connection.e_tag = etag # reset to the original data source connection - with pytest.raises(HttpResponseError): - client.delete_data_source_connection(data_source_connection, match_condition=MatchConditions.IfNotModified) - - def _test_delete_datasource_string_if_unchanged(self, client, storage_cs): - ds_name = "delstrunch" - data_source_connection = self._create_data_source_connection(storage_cs, ds_name) - created = client.create_data_source_connection(data_source_connection) - etag = created.e_tag - - # Now update the data source connection - data_source_connection.description = "updated" - client.create_or_update_data_source_connection(data_source_connection) - - # prepare data source connection - data_source_connection.e_tag = etag # reset to the original data source connection - with pytest.raises(ValueError): - client.delete_data_source_connection( - data_source_connection.name, - match_condition=MatchConditions.IfNotModified, - ) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py deleted file mode 100644 index 149e4d46944c..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py +++ /dev/null @@ -1,185 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes.models import ( - AnalyzeTextOptions, - CorsOptions, - SearchIndex, - ScoringProfile, - SimpleField, - SearchFieldDataType, -) -from azure.search.documents.indexes import SearchIndexClient -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchIndexClient(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema=None, index_batch=None) - @recorded_by_proxy - def test_search_index_client(self, endpoint, index_name): - client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) - index_name = "hotels" - self._test_get_service_statistics(client) - self._test_list_indexes_empty(client) - self._test_create_index(client, index_name) - self._test_list_indexes(client, index_name) - self._test_get_index(client, index_name) - self._test_get_index_statistics(client, index_name) - self._test_delete_indexes_if_unchanged(client) - self._test_create_or_update_index(client) - self._test_create_or_update_indexes_if_unchanged(client) - self._test_analyze_text(client, index_name) - self._test_delete_indexes(client) - - def _test_get_service_statistics(self, client): - result = client.get_service_statistics() - assert isinstance(result, dict) - assert set(result.keys()) == {"counters", "limits"} - - def _test_list_indexes_empty(self, client): - result = client.list_indexes() - with pytest.raises(StopIteration): - next(result) - - def _test_list_indexes(self, client, index_name): - result = client.list_indexes() - first = next(result) - assert first.name == index_name - - with pytest.raises(StopIteration): - next(result) - - def _test_get_index(self, client, index_name): - result = client.get_index(index_name) - assert result.name == index_name - - def _test_get_index_statistics(self, client, index_name): - result = client.get_index_statistics(index_name) - keys = set(result.keys()) - assert "document_count" in keys - assert "storage_size" in keys - assert "vector_index_size" in keys - - def _test_create_index(self, client, index_name): - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=index_name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = client.create_index(index) - assert result.name == index_name - assert result.scoring_profiles[0].name == scoring_profile.name - assert result.cors_options.allowed_origins == cors_options.allowed_origins - assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds - - def _test_create_or_update_index(self, client): - name = "hotels-cou" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profiles = [] - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = client.create_or_update_index(index=index) - assert len(result.scoring_profiles) == 0 - assert result.cors_options.allowed_origins == cors_options.allowed_origins - assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = client.create_or_update_index(index=index) - assert result.scoring_profiles[0].name == scoring_profile.name - assert result.cors_options.allowed_origins == cors_options.allowed_origins - assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds - - def _test_create_or_update_indexes_if_unchanged(self, client): - # First create an index - name = "hotels-coa-unchanged" - fields = [ - {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, - {"name": "baseRate", "type": "Edm.Double"}, - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = client.create_index(index) - etag = result.e_tag - # get e tag and update - index.scoring_profiles = [] - client.create_or_update_index(index) - - index.e_tag = etag - with pytest.raises(HttpResponseError): - client.create_or_update_index(index, match_condition=MatchConditions.IfNotModified) - - def _test_analyze_text(self, client, index_name): - analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") - result = client.analyze_text(index_name, analyze_request) - assert len(result.tokens) == 2 - - def _test_delete_indexes_if_unchanged(self, client): - # First create an index - name = "hotels-del-unchanged" - fields = [ - {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, - {"name": "baseRate", "type": "Edm.Double"}, - ] - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - index = SearchIndex( - name=name, - fields=fields, - scoring_profiles=scoring_profiles, - cors_options=cors_options, - ) - result = client.create_index(index) - etag = result.e_tag - # get e tag and update - index.scoring_profiles = [] - client.create_or_update_index(index) - - index.e_tag = etag - with pytest.raises(HttpResponseError): - client.delete_index(index, match_condition=MatchConditions.IfNotModified) - - def _test_delete_indexes(self, client): - for index in client.list_indexes(): - client.delete_index(index) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py deleted file mode 100644 index 284ce51594e5..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py +++ /dev/null @@ -1,252 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.core.credentials import AzureKeyCredential -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential -from search_service_preparer import SearchEnvVarPreparer, search_decorator -from azure.search.documents.indexes.models import ( - EntityLinkingSkill, - EntityRecognitionSkill, - EntityRecognitionSkillVersion, - InputFieldMappingEntry, - OutputFieldMappingEntry, - SearchIndexerSkillset, - SentimentSkill, - SentimentSkillVersion, -) -from azure.search.documents.indexes import SearchIndexerClient - - -class TestSearchSkillset(AzureRecordedTestCase): - @pytest.mark.skip("The skills are deprecated") - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_skillset_crud(self, endpoint): - client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) - self._test_create_skillset_validation() - self._test_create_skillset(client) - self._test_get_skillset(client) - self._test_get_skillsets(client) - self._test_create_or_update_skillset(client) - self._test_create_or_update_skillset_if_unchanged(client) - self._test_create_or_update_skillset_inplace(client) - self._test_delete_skillset_if_unchanged(client) - self._test_delete_skillset(client) - - def _test_create_skillset_validation(self): - name = "test-ss-validation" - with pytest.raises(ValueError) as err: - client = SearchIndexerClient("fake_endpoint", AzureKeyCredential("fake_key")) - - s1 = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], - description="Skill Version 1", - model_version="1", - include_typeless_entities=True, - ) - - s2 = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], - skill_version=EntityRecognitionSkillVersion.LATEST, - description="Skill Version 3", - model_version="3", - include_typeless_entities=True, - ) - s3 = SentimentSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], - skill_version=SentimentSkillVersion.V1, - description="Sentiment V1", - include_opinion_mining=True, - ) - skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s3]), description="desc") - client.create_skillset(skillset) - assert "include_typeless_entities" in str(err.value) - assert "model_version" in str(err.value) - assert "include_opinion_mining" in str(err.value) - - def _test_create_skillset(self, client): - name = "test-ss-create" - s1 = EntityRecognitionSkill( - name="skill1", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], - description="Skill Version 1", - include_typeless_entities=True, - ) - - s2 = EntityRecognitionSkill( - name="skill2", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], - skill_version=EntityRecognitionSkillVersion.LATEST, - description="Skill Version 3", - model_version="3", - ) - s3 = SentimentSkill( - name="skill3", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], - skill_version=SentimentSkillVersion.V1, - description="Sentiment V1", - ) - - s4 = SentimentSkill( - name="skill4", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4")], - skill_version=SentimentSkillVersion.V3, - description="Sentiment V3", - include_opinion_mining=True, - ) - - s5 = EntityLinkingSkill( - name="skill5", - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="entities", target_name="entitiesS5")], - minimum_precision=0.5, - ) - - skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s3, s4, s5]), description="desc") - - dict_skills = [skill.as_dict() for skill in skillset.skills] - skillset.skills = dict_skills - - result = client.create_skillset(skillset) - - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc" - assert result.e_tag - assert len(result.skills) == 5 - assert isinstance(result.skills[0], EntityRecognitionSkill) - assert result.skills[0].skill_version == EntityRecognitionSkillVersion.V1 - assert isinstance(result.skills[1], EntityRecognitionSkill) - assert result.skills[1].skill_version == EntityRecognitionSkillVersion.V3 - assert isinstance(result.skills[2], SentimentSkill) - assert result.skills[2].skill_version == SentimentSkillVersion.V1 - assert isinstance(result.skills[3], SentimentSkill) - assert result.skills[3].skill_version == SentimentSkillVersion.V3 - assert isinstance(result.skills[4], EntityLinkingSkill) - assert result.skills[4].minimum_precision == 0.5 - - assert len(client.get_skillsets()) == 1 - client.reset_skills(result, [x.name for x in result.skills]) - - def _test_get_skillset(self, client): - name = "test-ss-get" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") - client.create_skillset(skillset) - result = client.get_skillset(name) - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc" - assert result.e_tag - assert len(result.skills) == 1 - assert isinstance(result.skills[0], EntityRecognitionSkill) - - def _test_get_skillsets(self, client): - name1 = "test-ss-list-1" - name2 = "test-ss-list-2" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name1, skills=list([s]), description="desc1") - client.create_skillset(skillset1) - skillset2 = SearchIndexerSkillset(name=name2, skills=list([s]), description="desc2") - client.create_skillset(skillset2) - result = client.get_skillsets() - assert isinstance(result, list) - assert all(isinstance(x, SearchIndexerSkillset) for x in result) - assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) - - def _test_create_or_update_skillset(self, client): - name = "test-ss-create-or-update" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") - client.create_or_update_skillset(skillset1) - expected_count = len(client.get_skillsets()) - skillset2 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc2") - client.create_or_update_skillset(skillset2) - assert len(client.get_skillsets()) == expected_count - - result = client.get_skillset(name) - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc2" - - def _test_create_or_update_skillset_inplace(self, client): - name = "test-ss-create-or-update-inplace" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") - ss = client.create_or_update_skillset(skillset1) - expected_count = len(client.get_skillsets()) - skillset2 = SearchIndexerSkillset(name=name, skills=[s], description="desc2", skillset=ss) - client.create_or_update_skillset(skillset2) - assert len(client.get_skillsets()) == expected_count - - result = client.get_skillset(name) - assert isinstance(result, SearchIndexerSkillset) - assert result.name == name - assert result.description == "desc2" - - def _test_create_or_update_skillset_if_unchanged(self, client): - name = "test-ss-create-or-update-unchanged" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") - ss = client.create_or_update_skillset(skillset1) - - ss.e_tag = "changed_etag" - - with pytest.raises(HttpResponseError): - client.create_or_update_skillset(ss, match_condition=MatchConditions.IfNotModified) - - def _test_delete_skillset_if_unchanged(self, client): - name = "test-ss-deleted-unchanged" - s = EntityRecognitionSkill( - inputs=[InputFieldMappingEntry(name="text", source="/document/content")], - outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], - ) - - skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") - - result = client.create_skillset(skillset) - etag = result.e_tag - - skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="updated") - updated = client.create_or_update_skillset(skillset) - updated.e_tag = etag - - with pytest.raises(HttpResponseError): - client.delete_skillset(updated, match_condition=MatchConditions.IfNotModified) - - def _test_delete_skillset(self, client): - for skillset in client.get_skillset_names(): - client.delete_skillset(skillset) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py deleted file mode 100644 index 42a4154b0f45..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py +++ /dev/null @@ -1,145 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import pytest - -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes import SearchIndexClient -from azure.search.documents.indexes.models import SynonymMap -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchClientSynonymMaps(AzureRecordedTestCase): - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_synonym_map(self, endpoint): - client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) - self._test_create_synonym_map(client) - self._test_delete_synonym_map(client) - self._test_delete_synonym_map_if_unchanged(client) - self._test_get_synonym_map(client) - self._test_get_synonym_maps(client) - self._test_create_or_update_synonym_map(client) - - def _test_create_synonym_map(self, client): - expected = len(client.get_synonym_maps()) + 1 - name = "synmap-create" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - result = client.create_synonym_map(synonym_map) - assert isinstance(result, SynonymMap) - assert result.name == name - assert result.synonyms == [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - assert len(client.get_synonym_maps()) == expected - client.delete_synonym_map(name) - - def _test_delete_synonym_map(self, client): - name = "synmap-del" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - result = client.create_synonym_map(synonym_map) - expected = len(client.get_synonym_maps()) - 1 - client.delete_synonym_map(name) - assert len(client.get_synonym_maps()) == expected - - def _test_delete_synonym_map_if_unchanged(self, client): - name = "synmap-delunch" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - result = client.create_synonym_map(synonym_map) - etag = result.e_tag - - synonym_map.synonyms = "\n".join( - [ - "Washington, Wash. => WA", - ] - ) - client.create_or_update_synonym_map(synonym_map) - - result.e_tag = etag - with pytest.raises(HttpResponseError): - client.delete_synonym_map(result, match_condition=MatchConditions.IfNotModified) - client.delete_synonym_map(name) - - def _test_get_synonym_map(self, client): - expected = len(client.get_synonym_maps()) + 1 - name = "synmap-get" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - client.create_synonym_map(synonym_map) - assert len(client.get_synonym_maps()) == expected - result = client.get_synonym_map(name) - assert isinstance(result, SynonymMap) - assert result.name == name - assert result.synonyms == [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - client.delete_synonym_map(name) - - def _test_get_synonym_maps(self, client): - name1 = "synmap-list1" - name2 = "synmap-list2" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map_1 = SynonymMap(name=name1, synonyms=synonyms) - client.create_synonym_map(synonym_map_1) - synonyms = [ - "Washington, Wash. => WA", - ] - synonym_map_2 = SynonymMap(name=name2, synonyms=synonyms) - client.create_synonym_map(synonym_map_2) - result = client.get_synonym_maps() - assert isinstance(result, list) - assert all(isinstance(x, SynonymMap) for x in result) - expected = set([name1, name2]) - assert set(x.name for x in result).intersection(expected) == expected - client.delete_synonym_map(name1) - client.delete_synonym_map(name2) - - def _test_create_or_update_synonym_map(self, client): - expected = len(client.get_synonym_maps()) + 1 - name = "synmap-cou" - synonyms = [ - "USA, United States, United States of America", - "Washington, Wash. => WA", - ] - synonym_map = SynonymMap(name=name, synonyms=synonyms) - client.create_synonym_map(synonym_map) - assert len(client.get_synonym_maps()) == expected - synonym_map.synonyms = [ - "Washington, Wash. => WA", - ] - client.create_or_update_synonym_map(synonym_map) - assert len(client.get_synonym_maps()) == expected - result = client.get_synonym_map(name) - assert isinstance(result, SynonymMap) - assert result.name == name - assert result.synonyms == [ - "Washington, Wash. => WA", - ] - client.delete_synonym_map(name) diff --git a/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py b/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py deleted file mode 100644 index 5dc6daacdab2..000000000000 --- a/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py +++ /dev/null @@ -1,158 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import time - -import pytest -from azure.core import MatchConditions -from azure.core.exceptions import HttpResponseError -from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient -from azure.search.documents.indexes.models import ( - SearchIndex, - SearchIndexer, - SearchIndexerDataContainer, - SearchIndexerDataSourceConnection, -) -from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential - -from search_service_preparer import SearchEnvVarPreparer, search_decorator - - -class TestSearchIndexerClientTest(AzureRecordedTestCase): - @pytest.mark.skip("fails because connection string of storage is disabled") - @SearchEnvVarPreparer() - @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") - @recorded_by_proxy - def test_search_indexers(self, endpoint, **kwargs): - storage_cs = kwargs.get("search_storage_connection_string") - container_name = kwargs.get("search_storage_container_name") - client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) - index_client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) - self._test_create_indexer(client, index_client, storage_cs, container_name) - self._test_delete_indexer(client, index_client, storage_cs, container_name) - self._test_get_indexer(client, index_client, storage_cs, container_name) - self._test_list_indexer(client, index_client, storage_cs, container_name) - self._test_create_or_update_indexer(client, index_client, storage_cs, container_name) - self._test_reset_indexer(client, index_client, storage_cs, container_name) - self._test_run_indexer(client, index_client, storage_cs, container_name) - self._test_get_indexer_status(client, index_client, storage_cs, container_name) - self._test_create_or_update_indexer_if_unchanged(client, index_client, storage_cs, container_name) - self._test_delete_indexer_if_unchanged(client, index_client, storage_cs, container_name) - - def _prepare_indexer(self, client, index_client, storage_cs, name, container_name): - data_source_connection = SearchIndexerDataSourceConnection( - name=f"{name}-ds", - type="azureblob", - connection_string=storage_cs, - container=SearchIndexerDataContainer(name=container_name), - ) - ds = client.create_data_source_connection(data_source_connection) - - fields = [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}] - index = SearchIndex(name=f"{name}-hotels", fields=fields) - ind = index_client.create_index(index) - return SearchIndexer(name=name, data_source_name=ds.name, target_index_name=ind.name) - - def _test_create_indexer(self, client, index_client, storage_cs, container_name): - name = "create" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - result = client.create_indexer(indexer) - assert result.name == name - assert result.target_index_name == f"{name}-hotels" - assert result.data_source_name == f"{name}-ds" - - def _test_delete_indexer(self, client, index_client, storage_cs, container_name): - name = "delete" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - client.create_indexer(indexer) - expected = len(client.get_indexers()) - 1 - client.delete_indexer(name) - assert len(client.get_indexers()) == expected - - def _test_get_indexer(self, client, index_client, storage_cs, container_name): - name = "get" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - client.create_indexer(indexer) - result = client.get_indexer(name) - assert result.name == name - - def _test_list_indexer(self, client, index_client, storage_cs, container_name): - name1 = "list1" - name2 = "list2" - indexer1 = self._prepare_indexer(client, index_client, storage_cs, name1, container_name) - indexer2 = self._prepare_indexer(client, index_client, storage_cs, name2, container_name) - client.create_indexer(indexer1) - client.create_indexer(indexer2) - result = client.get_indexers() - assert isinstance(result, list) - assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) - - def _test_create_or_update_indexer(self, client, index_client, storage_cs, container_name): - name = "cou" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - client.create_indexer(indexer) - expected = len(client.get_indexers()) - if self.is_live: - time.sleep(10) - indexer.description = "updated" - client.create_or_update_indexer(indexer) - assert len(client.get_indexers()) == expected - result = client.get_indexer(name) - assert result.name == name - assert result.description == "updated" - - def _test_reset_indexer(self, client, index_client, storage_cs, container_name): - name = "reset" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - client.create_indexer(indexer) - if self.is_live: - time.sleep(10) - client.reset_indexer(name) - assert (client.get_indexer_status(name)).last_result.status.lower() in ( - "inprogress", - "reset", - ) - - def _test_run_indexer(self, client, index_client, storage_cs, container_name): - name = "run" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - client.create_indexer(indexer) - client.run_indexer(name) - assert (client.get_indexer_status(name)).status == "running" - - def _test_get_indexer_status(self, client, index_client, storage_cs, container_name): - name = "get-status" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - client.create_indexer(indexer) - status = client.get_indexer_status(name) - assert status.status is not None - - def _test_create_or_update_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): - name = "couunch" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - created = client.create_indexer(indexer) - etag = created.e_tag - if self.is_live: - time.sleep(10) - indexer.description = "updated" - client.create_or_update_indexer(indexer) - - indexer.e_tag = etag - with pytest.raises(HttpResponseError): - client.create_or_update_indexer(indexer, match_condition=MatchConditions.IfNotModified) - - def _test_delete_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): - name = "delunch" - indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) - result = client.create_indexer(indexer) - etag = result.e_tag - if self.is_live: - time.sleep(10) - indexer.description = "updated" - client.create_or_update_indexer(indexer) - - indexer.e_tag = etag - with pytest.raises(HttpResponseError): - client.delete_indexer(indexer, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/test_serialization.py b/sdk/search/azure-search-documents/tests/test_serialization.py deleted file mode 100644 index 09a5f04caf32..000000000000 --- a/sdk/search/azure-search-documents/tests/test_serialization.py +++ /dev/null @@ -1,108 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -from azure.search.documents.indexes.models import ( - SearchIndex, - SearchIndexerSkillset, - SearchFieldDataType, - SimpleField, - SearchableField, - ComplexField, - ScoringProfile, - CorsOptions, - CognitiveServicesAccountKey, - InputFieldMappingEntry, - OutputFieldMappingEntry, - SearchIndexerSkillset, - SplitSkill, - TextSplitMode, -) - - -def test_serialize_search_index(): - new_index_name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - SearchableField(name="hotelName", type=SearchFieldDataType.String), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex( - name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options - ) - search_index_serialized = index.serialize() - search_index = SearchIndex.deserialize(search_index_serialized) - assert search_index - - -def test_serialize_search_indexer_skillset(): - COGNITIVE_KEY = ... - COGNITIVE_DESCRIPTION = ... - - cognitive_services_account = CognitiveServicesAccountKey(key=COGNITIVE_KEY, description=COGNITIVE_DESCRIPTION) - - inputs = [InputFieldMappingEntry(name="text", source="/document/content")] - - outputs = [OutputFieldMappingEntry(name="textItems", target_name="pages")] - - split_skill = SplitSkill( - name="SplitSkill", - inputs=inputs, - outputs=outputs, - context="/document", - text_split_mode=TextSplitMode.PAGES, - maximum_page_length=5000, - ) - - skills = [split_skill] - skillset = SearchIndexerSkillset( - name="Skillset", skills=skills, cognitive_services_account=cognitive_services_account - ) - - serialized_skillset = skillset.serialize() - skillset = SearchIndexerSkillset.deserialize(serialized_skillset) - assert skillset - - -def test_serialize_search_index_dict(): - new_index_name = "hotels" - fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), - SimpleField(name="baseRate", type=SearchFieldDataType.Double), - SearchableField(name="description", type=SearchFieldDataType.String, collection=True), - SearchableField(name="hotelName", type=SearchFieldDataType.String), - ComplexField( - name="address", - fields=[ - SimpleField(name="streetAddress", type=SearchFieldDataType.String), - SimpleField(name="city", type=SearchFieldDataType.String), - SimpleField(name="state", type=SearchFieldDataType.String), - ], - collection=True, - ), - ] - cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) - scoring_profile = ScoringProfile(name="MyProfile") - scoring_profiles = [] - scoring_profiles.append(scoring_profile) - index = SearchIndex( - name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options - ) - search_index_serialized_dict = index.as_dict() - search_index = SearchIndex.from_dict(search_index_serialized_dict) - assert search_index From 13053adb979eedcb1c014e6c3452d4dbb92b1d9c Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Thu, 23 Oct 2025 15:14:08 -0700 Subject: [PATCH 02/40] updates --- .../azure/search/documents/_client.py | 7 +- .../operations => _operations}/__init__.py | 6 +- .../_operations.py | 143 +- .../{aio/operations => _operations}/_patch.py | 0 .../azure/search/documents/_patch.py | 10 +- .../azure/search/documents/_version.py | 2 +- .../azure/search/documents/aio/_client.py | 7 +- .../_operations}/__init__.py | 6 +- .../_operations.py | 142 +- .../operations => aio/_operations}/_patch.py | 0 .../search/documents/indexes/__init__.py | 2 + .../azure/search/documents/indexes/_client.py | 119 +- .../documents/indexes/_configuration.py | 55 + .../documents/indexes/_operations/__init__.py | 24 + .../_operations.py | 5513 ++++++++--------- .../{operations => _operations}/_patch.py | 0 .../search/documents/indexes/aio/__init__.py | 2 + .../search/documents/indexes/aio/_client.py | 123 +- .../documents/indexes/aio/_configuration.py | 57 + .../indexes/aio/_operations/__init__.py | 24 + .../_operations.py | 4920 +++++++-------- .../aio/_operations}/_patch.py | 0 .../indexes/aio/operations/__init__.py | 40 - .../documents/indexes/models/__init__.py | 8 +- .../documents/indexes/models/_models.py | 210 +- .../search/documents/indexes/models/_patch.py | 571 +- .../documents/indexes/operations/__init__.py | 40 - .../search/documents/knowledgebase/_client.py | 9 +- .../{operations => _operations}/__init__.py | 6 +- .../_operations.py | 29 +- .../{operations => _operations}/_patch.py | 0 .../documents/knowledgebase/aio/_client.py | 10 +- .../{operations => _operations}/__init__.py | 6 +- .../_operations.py | 31 +- .../aio/_operations}/_patch.py | 0 .../azure/search/documents/models/_models.py | 30 +- .../azure-search-documents/samples/README.md | 73 + .../sample_analyze_text_async.py | 47 + .../sample_authentication_async.py | 91 + .../sample_autocomplete_async.py | 49 + .../sample_buffered_sender_async.py | 56 + .../sample_crud_operations_async.py | 73 + .../sample_data_source_operations_async.py | 81 + .../async_samples/sample_facet_query_async.py | 52 + .../sample_filter_query_async.py | 54 + .../sample_get_document_async.py | 48 + ...ample_index_alias_crud_operations_async.py | 111 + .../sample_index_client_send_request_async.py | 49 + .../sample_index_crud_operations_async.py | 127 + .../sample_indexers_operations_async.py | 132 + .../sample_query_session_async.py | 49 + ...sample_search_client_send_request_async.py | 49 + .../sample_semantic_search_async.py | 71 + .../sample_simple_query_async.py | 49 + .../async_samples/sample_suggestions_async.py | 50 + .../sample_synonym_map_operations_async.py | 80 + .../sample_vector_search_async.py | 203 + .../samples/batch_upload.py | 10 + .../samples/files/hotel_small.json | 252 + .../samples/sample_analyze_text.py | 45 + .../samples/sample_authentication.py | 89 + .../samples/sample_autocomplete.py | 46 + .../samples/sample_buffered_sender.py | 51 + .../samples/sample_crud_operations.py | 67 + .../samples/sample_data_source_operations.py | 72 + .../samples/sample_facet_query.py | 49 + .../samples/sample_filter_query.py | 51 + .../samples/sample_get_document.py | 45 + .../sample_index_alias_crud_operations.py | 105 + .../sample_index_client_send_request.py | 47 + .../samples/sample_index_crud_operations.py | 116 + .../sample_indexer_datasource_skillset.py | 152 + .../samples/sample_indexers_operations.py | 123 + .../samples/sample_query_session.py | 47 + .../sample_search_client_send_request.py | 47 + .../samples/sample_semantic_search.py | 70 + .../samples/sample_simple_query.py | 46 + .../samples/sample_suggestions.py | 47 + .../samples/sample_synonym_map_operations.py | 89 + .../samples/sample_vector_search.py | 204 + .../samples/simple_query.py | 66 + .../samples/synonym_map.txt | 2 + 82 files changed, 9727 insertions(+), 5957 deletions(-) rename sdk/search/azure-search-documents/azure/search/documents/{aio/operations => _operations}/__init__.py (87%) rename sdk/search/azure-search-documents/azure/search/documents/{operations => _operations}/_operations.py (96%) rename sdk/search/azure-search-documents/azure/search/documents/{aio/operations => _operations}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/{operations => aio/_operations}/__init__.py (87%) rename sdk/search/azure-search-documents/azure/search/documents/aio/{operations => _operations}/_operations.py (95%) rename sdk/search/azure-search-documents/azure/search/documents/{indexes/aio/operations => aio/_operations}/_patch.py (100%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/{operations => _operations}/_operations.py (91%) rename sdk/search/azure-search-documents/azure/search/documents/indexes/{operations => _operations}/_patch.py (100%) create mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py rename sdk/search/azure-search-documents/azure/search/documents/indexes/aio/{operations => _operations}/_operations.py (89%) rename sdk/search/azure-search-documents/azure/search/documents/{knowledgebase/aio/operations => indexes/aio/_operations}/_patch.py (100%) delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py delete mode 100644 sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py rename sdk/search/azure-search-documents/azure/search/documents/knowledgebase/{operations => _operations}/__init__.py (86%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebase/{operations => _operations}/_operations.py (91%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebase/{operations => _operations}/_patch.py (100%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/{operations => _operations}/__init__.py (86%) rename sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/{operations => _operations}/_operations.py (89%) rename sdk/search/azure-search-documents/azure/search/documents/{operations => knowledgebase/aio/_operations}/_patch.py (100%) create mode 100644 sdk/search/azure-search-documents/samples/README.md create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py create mode 100644 sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py create mode 100644 sdk/search/azure-search-documents/samples/batch_upload.py create mode 100644 sdk/search/azure-search-documents/samples/files/hotel_small.json create mode 100644 sdk/search/azure-search-documents/samples/sample_analyze_text.py create mode 100644 sdk/search/azure-search-documents/samples/sample_authentication.py create mode 100644 sdk/search/azure-search-documents/samples/sample_autocomplete.py create mode 100644 sdk/search/azure-search-documents/samples/sample_buffered_sender.py create mode 100644 sdk/search/azure-search-documents/samples/sample_crud_operations.py create mode 100644 sdk/search/azure-search-documents/samples/sample_data_source_operations.py create mode 100644 sdk/search/azure-search-documents/samples/sample_facet_query.py create mode 100644 sdk/search/azure-search-documents/samples/sample_filter_query.py create mode 100644 sdk/search/azure-search-documents/samples/sample_get_document.py create mode 100644 sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py create mode 100644 sdk/search/azure-search-documents/samples/sample_index_client_send_request.py create mode 100644 sdk/search/azure-search-documents/samples/sample_index_crud_operations.py create mode 100644 sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py create mode 100644 sdk/search/azure-search-documents/samples/sample_indexers_operations.py create mode 100644 sdk/search/azure-search-documents/samples/sample_query_session.py create mode 100644 sdk/search/azure-search-documents/samples/sample_search_client_send_request.py create mode 100644 sdk/search/azure-search-documents/samples/sample_semantic_search.py create mode 100644 sdk/search/azure-search-documents/samples/sample_simple_query.py create mode 100644 sdk/search/azure-search-documents/samples/sample_suggestions.py create mode 100644 sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py create mode 100644 sdk/search/azure-search-documents/samples/sample_vector_search.py create mode 100644 sdk/search/azure-search-documents/samples/simple_query.py create mode 100644 sdk/search/azure-search-documents/samples/synonym_map.txt diff --git a/sdk/search/azure-search-documents/azure/search/documents/_client.py b/sdk/search/azure-search-documents/azure/search/documents/_client.py index c5b9b7226926..5f688aa13b44 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_client.py @@ -16,18 +16,16 @@ from azure.core.rest import HttpRequest, HttpResponse from ._configuration import SearchClientConfiguration +from ._operations import _SearchClientOperationsMixin from ._utils.serialization import Deserializer, Serializer -from .operations import DocumentsOperations if TYPE_CHECKING: from azure.core.credentials import TokenCredential -class SearchClient: +class SearchClient(_SearchClientOperationsMixin): """SearchClient. - :ivar documents: DocumentsOperations operations - :vartype documents: azure.search.documents.operations.DocumentsOperations :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -72,7 +70,6 @@ def __init__( self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.documents = DocumentsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/__init__.py similarity index 87% rename from sdk/search/azure-search-documents/azure/search/documents/aio/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_operations/__init__.py index e7e958355b4b..3d57eee2949f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/__init__.py @@ -12,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import DocumentsOperations # type: ignore +from ._operations import _SearchClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "DocumentsOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py similarity index 96% rename from sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index 74358c90b5ca..282f90740feb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -30,19 +30,19 @@ from .. import models as _models1 from .._configuration import SearchClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize -from .._utils.serialization import Deserializer, Serializer +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC from .._validation import api_version_validation JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_documents_count_request( +def build_search_get_document_count_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -72,26 +72,26 @@ def build_documents_count_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_search_get_request( +def build_search_search_get_request( index_name: str, *, search_text: Optional[str] = None, include_total_result_count: Optional[bool] = None, - facets: Optional[List[str]] = None, + facets: Optional[list[str]] = None, filter: Optional[str] = None, - highlight_fields: Optional[List[str]] = None, + highlight_fields: Optional[list[str]] = None, highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, + order_by: Optional[list[str]] = None, query_type: Optional[Union[str, _models1.QueryType]] = None, - scoring_parameters: Optional[List[str]] = None, + scoring_parameters: Optional[list[str]] = None, scoring_profile: Optional[str] = None, - search_fields: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, search_mode: Optional[Union[str, _models1.SearchMode]] = None, scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, session_id: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, skip: Optional[int] = None, top: Optional[int] = None, semantic_configuration: Optional[str] = None, @@ -104,7 +104,7 @@ def build_documents_search_get_request( debug: Optional[Union[str, _models1.QueryDebugMode]] = None, query_language: Optional[Union[str, _models1.QueryLanguage]] = None, speller: Optional[Union[str, _models1.QuerySpellerType]] = None, - semantic_fields: Optional[List[str]] = None, + semantic_fields: Optional[list[str]] = None, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: @@ -199,7 +199,7 @@ def build_documents_search_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_search_post_request( +def build_search_search_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -232,11 +232,11 @@ def build_documents_search_post_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_get_request( +def build_search_get_document_request( key: str, index_name: str, *, - selected_fields: Optional[List[str]] = None, + selected_fields: Optional[list[str]] = None, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: @@ -270,7 +270,7 @@ def build_documents_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_suggest_get_request( +def build_search_suggest_get_request( index_name: str, *, search_text: str, @@ -280,9 +280,9 @@ def build_documents_suggest_get_request( highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any @@ -334,7 +334,7 @@ def build_documents_suggest_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_suggest_post_request( +def build_search_suggest_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -367,7 +367,7 @@ def build_documents_suggest_post_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_index_request( +def build_search_index_documents_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -400,7 +400,7 @@ def build_documents_index_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_autocomplete_get_request( +def build_search_autocomplete_get_request( index_name: str, *, search_text: str, @@ -411,7 +411,7 @@ def build_documents_autocomplete_get_request( highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - search_fields: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any @@ -461,7 +461,7 @@ def build_documents_autocomplete_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_documents_autocomplete_post_request( # pylint: disable=name-too-long +def build_search_autocomplete_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -494,25 +494,12 @@ def build_documents_autocomplete_post_request( # pylint: disable=name-too-long return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class DocumentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchClient`'s - :attr:`documents` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _SearchClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchClientConfiguration] +): @distributed_trace - def count(self, *, query_source_authorization: Optional[str] = None, **kwargs: Any) -> int: + def get_document_count(self, *, query_source_authorization: Optional[str] = None, **kwargs: Any) -> int: """Queries the number of documents in the index. :keyword query_source_authorization: Token identifying the user for which the query is being @@ -536,7 +523,7 @@ def count(self, *, query_source_authorization: Optional[str] = None, **kwargs: A cls: ClsType[int] = kwargs.pop("cls", None) - _request = build_documents_count_request( + _request = build_search_get_document_count_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, api_version=self._config.api_version, @@ -587,21 +574,21 @@ def search_get( *, search_text: Optional[str] = None, include_total_result_count: Optional[bool] = None, - facets: Optional[List[str]] = None, + facets: Optional[list[str]] = None, filter: Optional[str] = None, - highlight_fields: Optional[List[str]] = None, + highlight_fields: Optional[list[str]] = None, highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, + order_by: Optional[list[str]] = None, query_type: Optional[Union[str, _models1.QueryType]] = None, - scoring_parameters: Optional[List[str]] = None, + scoring_parameters: Optional[list[str]] = None, scoring_profile: Optional[str] = None, - search_fields: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, search_mode: Optional[Union[str, _models1.SearchMode]] = None, scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, session_id: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, skip: Optional[int] = None, top: Optional[int] = None, semantic_configuration: Optional[str] = None, @@ -614,7 +601,7 @@ def search_get( debug: Optional[Union[str, _models1.QueryDebugMode]] = None, query_language: Optional[Union[str, _models1.QueryLanguage]] = None, speller: Optional[Union[str, _models1.QuerySpellerType]] = None, - semantic_fields: Optional[List[str]] = None, + semantic_fields: Optional[list[str]] = None, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> _models1.SearchDocumentsResult: @@ -785,7 +772,7 @@ def search_get( cls: ClsType[_models1.SearchDocumentsResult] = kwargs.pop("cls", None) - _request = build_documents_search_get_request( + _request = build_search_search_get_request( index_name=self._config.index_name, search_text=search_text, include_total_result_count=include_total_result_count, @@ -855,7 +842,7 @@ def search_get( return deserialized # type: ignore @overload - def search_post( + def search( self, search_request: _models1.SearchRequest, *, @@ -880,7 +867,7 @@ def search_post( """ @overload - def search_post( + def search( self, search_request: JSON, *, @@ -905,7 +892,7 @@ def search_post( """ @overload - def search_post( + def search( self, search_request: IO[bytes], *, @@ -930,7 +917,7 @@ def search_post( """ @distributed_trace - def search_post( + def search( self, search_request: Union[_models1.SearchRequest, JSON, IO[bytes]], *, @@ -971,7 +958,7 @@ def search_post( else: _content = json.dumps(search_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_search_post_request( + _request = build_search_search_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1013,11 +1000,11 @@ def search_post( return deserialized # type: ignore @distributed_trace - def get( + def get_document( self, key: str, *, - selected_fields: Optional[List[str]] = None, + selected_fields: Optional[list[str]] = None, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> _models1.LookupDocument: @@ -1049,7 +1036,7 @@ def get( cls: ClsType[_models1.LookupDocument] = kwargs.pop("cls", None) - _request = build_documents_get_request( + _request = build_search_get_document_request( key=key, index_name=self._config.index_name, selected_fields=selected_fields, @@ -1101,9 +1088,9 @@ def suggest_get( highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any @@ -1175,7 +1162,7 @@ def suggest_get( cls: ClsType[_models1.SuggestDocumentsResult] = kwargs.pop("cls", None) - _request = build_documents_suggest_get_request( + _request = build_search_suggest_get_request( index_name=self._config.index_name, search_text=search_text, suggester_name=suggester_name, @@ -1226,7 +1213,7 @@ def suggest_get( return deserialized # type: ignore @overload - def suggest_post( + def suggest( self, suggest_request: _models1.SuggestRequest, *, @@ -1251,7 +1238,7 @@ def suggest_post( """ @overload - def suggest_post( + def suggest( self, suggest_request: JSON, *, @@ -1276,7 +1263,7 @@ def suggest_post( """ @overload - def suggest_post( + def suggest( self, suggest_request: IO[bytes], *, @@ -1301,7 +1288,7 @@ def suggest_post( """ @distributed_trace - def suggest_post( + def suggest( self, suggest_request: Union[_models1.SuggestRequest, JSON, IO[bytes]], *, @@ -1342,7 +1329,7 @@ def suggest_post( else: _content = json.dumps(suggest_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_suggest_post_request( + _request = build_search_suggest_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1384,7 +1371,7 @@ def suggest_post( return deserialized # type: ignore @overload - def index( + def index_documents( self, batch: _models1.IndexBatch, *, @@ -1409,7 +1396,7 @@ def index( """ @overload - def index( + def index_documents( self, batch: JSON, *, @@ -1434,7 +1421,7 @@ def index( """ @overload - def index( + def index_documents( self, batch: IO[bytes], *, @@ -1459,7 +1446,7 @@ def index( """ @distributed_trace - def index( + def index_documents( self, batch: Union[_models1.IndexBatch, JSON, IO[bytes]], *, @@ -1500,7 +1487,7 @@ def index( else: _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_index_request( + _request = build_search_index_documents_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1553,7 +1540,7 @@ def autocomplete_get( highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - search_fields: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any @@ -1617,7 +1604,7 @@ def autocomplete_get( cls: ClsType[_models1.AutocompleteResult] = kwargs.pop("cls", None) - _request = build_documents_autocomplete_get_request( + _request = build_search_autocomplete_get_request( index_name=self._config.index_name, search_text=search_text, suggester_name=suggester_name, @@ -1667,7 +1654,7 @@ def autocomplete_get( return deserialized # type: ignore @overload - def autocomplete_post( + def autocomplete( self, autocomplete_request: _models1.AutocompleteRequest, *, @@ -1692,7 +1679,7 @@ def autocomplete_post( """ @overload - def autocomplete_post( + def autocomplete( self, autocomplete_request: JSON, *, @@ -1717,7 +1704,7 @@ def autocomplete_post( """ @overload - def autocomplete_post( + def autocomplete( self, autocomplete_request: IO[bytes], *, @@ -1742,7 +1729,7 @@ def autocomplete_post( """ @distributed_trace - def autocomplete_post( + def autocomplete( self, autocomplete_request: Union[_models1.AutocompleteRequest, JSON, IO[bytes]], *, @@ -1784,7 +1771,7 @@ def autocomplete_post( else: _content = json.dumps(autocomplete_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_autocomplete_post_request( + _request = build_search_autocomplete_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index 87676c65a8f0..cbf30f0463a6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -7,9 +7,17 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from ._client import SearchClient as _SearchClient -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +class SearchClient(_SearchClient): + """SearchClient customizations go here.""" + + def __init__(self, endpoint, index_name, credential, **kwargs): + super().__init__(endpoint, credential, index_name, **kwargs) + + +__all__: list[str] = ["SearchClient"] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/_version.py b/sdk/search/azure-search-documents/azure/search/documents/_version.py index 80c9294bc018..8034a8e95766 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_version.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "11.7.0b2" +VERSION = "11.7.0b3" diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py index 427064b271ac..5634eb8a97d5 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_client.py @@ -17,17 +17,15 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import SearchClientConfiguration -from .operations import DocumentsOperations +from ._operations import _SearchClientOperationsMixin if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class SearchClient: +class SearchClient(_SearchClientOperationsMixin): """SearchClient. - :ivar documents: DocumentsOperations operations - :vartype documents: azure.search.documents.aio.operations.DocumentsOperations :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -76,7 +74,6 @@ def __init__( self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.documents = DocumentsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/sdk/search/azure-search-documents/azure/search/documents/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/__init__.py similarity index 87% rename from sdk/search/azure-search-documents/azure/search/documents/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_operations/__init__.py index e7e958355b4b..3d57eee2949f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/__init__.py @@ -12,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import DocumentsOperations # type: ignore +from ._operations import _SearchClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "DocumentsOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py similarity index 95% rename from sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index e04b0ff1cc1f..cd54121954c3 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -28,47 +28,33 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models2 +from ..._operations._operations import ( + build_search_autocomplete_get_request, + build_search_autocomplete_request, + build_search_get_document_count_request, + build_search_get_document_request, + build_search_index_documents_request, + build_search_search_get_request, + build_search_search_request, + build_search_suggest_get_request, + build_search_suggest_request, +) from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize -from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import ClientMixinABC from ..._validation import api_version_validation -from ...operations._operations import ( - build_documents_autocomplete_get_request, - build_documents_autocomplete_post_request, - build_documents_count_request, - build_documents_get_request, - build_documents_index_request, - build_documents_search_get_request, - build_documents_search_post_request, - build_documents_suggest_get_request, - build_documents_suggest_post_request, -) from .._configuration import SearchClientConfiguration JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list - - -class DocumentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchClient`'s - :attr:`documents` attribute. - """ - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _SearchClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchClientConfiguration] +): @distributed_trace_async - async def count(self, *, query_source_authorization: Optional[str] = None, **kwargs: Any) -> int: + async def get_document_count(self, *, query_source_authorization: Optional[str] = None, **kwargs: Any) -> int: """Queries the number of documents in the index. :keyword query_source_authorization: Token identifying the user for which the query is being @@ -92,7 +78,7 @@ async def count(self, *, query_source_authorization: Optional[str] = None, **kwa cls: ClsType[int] = kwargs.pop("cls", None) - _request = build_documents_count_request( + _request = build_search_get_document_count_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, api_version=self._config.api_version, @@ -105,7 +91,7 @@ async def count(self, *, query_source_authorization: Optional[str] = None, **kwa _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -143,21 +129,21 @@ async def search_get( *, search_text: Optional[str] = None, include_total_result_count: Optional[bool] = None, - facets: Optional[List[str]] = None, + facets: Optional[list[str]] = None, filter: Optional[str] = None, - highlight_fields: Optional[List[str]] = None, + highlight_fields: Optional[list[str]] = None, highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, + order_by: Optional[list[str]] = None, query_type: Optional[Union[str, _models2.QueryType]] = None, - scoring_parameters: Optional[List[str]] = None, + scoring_parameters: Optional[list[str]] = None, scoring_profile: Optional[str] = None, - search_fields: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, search_mode: Optional[Union[str, _models2.SearchMode]] = None, scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, session_id: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, skip: Optional[int] = None, top: Optional[int] = None, semantic_configuration: Optional[str] = None, @@ -170,7 +156,7 @@ async def search_get( debug: Optional[Union[str, _models2.QueryDebugMode]] = None, query_language: Optional[Union[str, _models2.QueryLanguage]] = None, speller: Optional[Union[str, _models2.QuerySpellerType]] = None, - semantic_fields: Optional[List[str]] = None, + semantic_fields: Optional[list[str]] = None, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> _models2.SearchDocumentsResult: @@ -341,7 +327,7 @@ async def search_get( cls: ClsType[_models2.SearchDocumentsResult] = kwargs.pop("cls", None) - _request = build_documents_search_get_request( + _request = build_search_search_get_request( index_name=self._config.index_name, search_text=search_text, include_total_result_count=include_total_result_count, @@ -384,7 +370,7 @@ async def search_get( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -411,7 +397,7 @@ async def search_get( return deserialized # type: ignore @overload - async def search_post( + async def search( self, search_request: _models2.SearchRequest, *, @@ -436,7 +422,7 @@ async def search_post( """ @overload - async def search_post( + async def search( self, search_request: JSON, *, @@ -461,7 +447,7 @@ async def search_post( """ @overload - async def search_post( + async def search( self, search_request: IO[bytes], *, @@ -486,7 +472,7 @@ async def search_post( """ @distributed_trace_async - async def search_post( + async def search( self, search_request: Union[_models2.SearchRequest, JSON, IO[bytes]], *, @@ -527,7 +513,7 @@ async def search_post( else: _content = json.dumps(search_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_search_post_request( + _request = build_search_search_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -542,7 +528,7 @@ async def search_post( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -569,11 +555,11 @@ async def search_post( return deserialized # type: ignore @distributed_trace_async - async def get( + async def get_document( self, key: str, *, - selected_fields: Optional[List[str]] = None, + selected_fields: Optional[list[str]] = None, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> _models2.LookupDocument: @@ -605,7 +591,7 @@ async def get( cls: ClsType[_models2.LookupDocument] = kwargs.pop("cls", None) - _request = build_documents_get_request( + _request = build_search_get_document_request( key=key, index_name=self._config.index_name, selected_fields=selected_fields, @@ -620,7 +606,7 @@ async def get( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -657,9 +643,9 @@ async def suggest_get( highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - order_by: Optional[List[str]] = None, - search_fields: Optional[List[str]] = None, - select: Optional[List[str]] = None, + order_by: Optional[list[str]] = None, + search_fields: Optional[list[str]] = None, + select: Optional[list[str]] = None, top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any @@ -731,7 +717,7 @@ async def suggest_get( cls: ClsType[_models2.SuggestDocumentsResult] = kwargs.pop("cls", None) - _request = build_documents_suggest_get_request( + _request = build_search_suggest_get_request( index_name=self._config.index_name, search_text=search_text, suggester_name=suggester_name, @@ -755,7 +741,7 @@ async def suggest_get( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -782,7 +768,7 @@ async def suggest_get( return deserialized # type: ignore @overload - async def suggest_post( + async def suggest( self, suggest_request: _models2.SuggestRequest, *, @@ -807,7 +793,7 @@ async def suggest_post( """ @overload - async def suggest_post( + async def suggest( self, suggest_request: JSON, *, @@ -832,7 +818,7 @@ async def suggest_post( """ @overload - async def suggest_post( + async def suggest( self, suggest_request: IO[bytes], *, @@ -857,7 +843,7 @@ async def suggest_post( """ @distributed_trace_async - async def suggest_post( + async def suggest( self, suggest_request: Union[_models2.SuggestRequest, JSON, IO[bytes]], *, @@ -898,7 +884,7 @@ async def suggest_post( else: _content = json.dumps(suggest_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_suggest_post_request( + _request = build_search_suggest_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -913,7 +899,7 @@ async def suggest_post( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -940,7 +926,7 @@ async def suggest_post( return deserialized # type: ignore @overload - async def index( + async def index_documents( self, batch: _models2.IndexBatch, *, @@ -965,7 +951,7 @@ async def index( """ @overload - async def index( + async def index_documents( self, batch: JSON, *, @@ -990,7 +976,7 @@ async def index( """ @overload - async def index( + async def index_documents( self, batch: IO[bytes], *, @@ -1015,7 +1001,7 @@ async def index( """ @distributed_trace_async - async def index( + async def index_documents( self, batch: Union[_models2.IndexBatch, JSON, IO[bytes]], *, @@ -1056,7 +1042,7 @@ async def index( else: _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_index_request( + _request = build_search_index_documents_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1071,7 +1057,7 @@ async def index( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1109,7 +1095,7 @@ async def autocomplete_get( highlight_post_tag: Optional[str] = None, highlight_pre_tag: Optional[str] = None, minimum_coverage: Optional[float] = None, - search_fields: Optional[List[str]] = None, + search_fields: Optional[list[str]] = None, top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any @@ -1173,7 +1159,7 @@ async def autocomplete_get( cls: ClsType[_models2.AutocompleteResult] = kwargs.pop("cls", None) - _request = build_documents_autocomplete_get_request( + _request = build_search_autocomplete_get_request( index_name=self._config.index_name, search_text=search_text, suggester_name=suggester_name, @@ -1196,7 +1182,7 @@ async def autocomplete_get( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1223,7 +1209,7 @@ async def autocomplete_get( return deserialized # type: ignore @overload - async def autocomplete_post( + async def autocomplete( self, autocomplete_request: _models2.AutocompleteRequest, *, @@ -1248,7 +1234,7 @@ async def autocomplete_post( """ @overload - async def autocomplete_post( + async def autocomplete( self, autocomplete_request: JSON, *, @@ -1273,7 +1259,7 @@ async def autocomplete_post( """ @overload - async def autocomplete_post( + async def autocomplete( self, autocomplete_request: IO[bytes], *, @@ -1298,7 +1284,7 @@ async def autocomplete_post( """ @distributed_trace_async - async def autocomplete_post( + async def autocomplete( self, autocomplete_request: Union[_models2.AutocompleteRequest, JSON, IO[bytes]], *, @@ -1340,7 +1326,7 @@ async def autocomplete_post( else: _content = json.dumps(autocomplete_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_documents_autocomplete_post_request( + _request = build_search_autocomplete_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1355,7 +1341,7 @@ async def autocomplete_post( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py index db78bf894037..064fb13712b1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/__init__.py @@ -13,6 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._client import SearchIndexClient # type: ignore +from ._client import SearchIndexerClient # type: ignore from .._version import VERSION __version__ = VERSION @@ -26,6 +27,7 @@ __all__ = [ "SearchIndexClient", + "SearchIndexerClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py index 84a3ae751f9f..54c2e85631d1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_client.py @@ -16,42 +16,16 @@ from azure.core.rest import HttpRequest, HttpResponse from .._utils.serialization import Deserializer, Serializer -from ._configuration import SearchIndexClientConfiguration -from .operations import ( - AgentsOperations, - AliasesOperations, - DataSourcesOperations, - IndexersOperations, - IndexesOperations, - SkillsetsOperations, - SourcesOperations, - SynonymMapsOperations, - _SearchIndexClientOperationsMixin, -) +from ._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration +from ._operations import _SearchIndexClientOperationsMixin, _SearchIndexerClientOperationsMixin if TYPE_CHECKING: from azure.core.credentials import TokenCredential -class SearchIndexClient(_SearchIndexClientOperationsMixin): # pylint: disable=too-many-instance-attributes +class SearchIndexClient(_SearchIndexClientOperationsMixin): """SearchIndexClient. - :ivar data_sources: DataSourcesOperations operations - :vartype data_sources: azure.search.documents.operations.DataSourcesOperations - :ivar indexers: IndexersOperations operations - :vartype indexers: azure.search.documents.operations.IndexersOperations - :ivar skillsets: SkillsetsOperations operations - :vartype skillsets: azure.search.documents.operations.SkillsetsOperations - :ivar synonym_maps: SynonymMapsOperations operations - :vartype synonym_maps: azure.search.documents.operations.SynonymMapsOperations - :ivar indexes: IndexesOperations operations - :vartype indexes: azure.search.documents.operations.IndexesOperations - :ivar aliases: AliasesOperations operations - :vartype aliases: azure.search.documents.operations.AliasesOperations - :ivar agents: AgentsOperations operations - :vartype agents: azure.search.documents.operations.AgentsOperations - :ivar sources: SourcesOperations operations - :vartype sources: azure.search.documents.operations.SourcesOperations :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -90,14 +64,85 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCr self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.data_sources = DataSourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexers = IndexersOperations(self._client, self._config, self._serialize, self._deserialize) - self.skillsets = SkillsetsOperations(self._client, self._config, self._serialize, self._deserialize) - self.synonym_maps = SynonymMapsOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) - self.aliases = AliasesOperations(self._client, self._config, self._serialize, self._deserialize) - self.agents = AgentsOperations(self._client, self._config, self._serialize, self._deserialize) - self.sources = SourcesOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) + + +class SearchIndexerClient(_SearchIndexerClientOperationsMixin): + """SearchIndexerClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = SearchIndexerClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py index 9993578ced46..a1c66e4d109e 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_configuration.py @@ -70,3 +70,58 @@ def _configure(self, **kwargs: Any) -> None: self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = self._infer_policy(**kwargs) + + +class SearchIndexerClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexerClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py new file mode 100644 index 000000000000..baa9bb7fd3fa --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _SearchIndexerClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py similarity index 91% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index a4892dc4f293..895baa0d7f80 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -33,27 +33,25 @@ from .. import models as _models1 from ... import models as _models2 from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize -from ..._utils.serialization import Deserializer, Serializer +from ..._utils.serialization import Serializer from ..._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match from ..._validation import api_version_validation -from .._configuration import SearchIndexClientConfiguration +from .._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_data_sources_create_or_update_request( # pylint: disable=name-too-long - data_source_name: str, +def build_search_index_create_or_update_synonym_map_request( # pylint: disable=name-too-long + synonym_map_name: str, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -64,19 +62,15 @@ def build_data_sources_create_or_update_request( # pylint: disable=name-too-lon accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/datasources('{dataSourceName}')" + _url = "/synonymmaps('{synonymMapName}')" path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), + "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) # Construct headers _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") @@ -93,21 +87,21 @@ def build_data_sources_create_or_update_request( # pylint: disable=name-too-lon return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_data_sources_delete_request( - data_source_name: str, +def build_search_index_delete_synonym_map_request( # pylint: disable=name-too-long + synonym_map_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/datasources('{dataSourceName}')" + _url = "/synonymmaps('{synonymMapName}')" path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), + "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -126,7 +120,9 @@ def build_data_sources_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_data_sources_get_request(data_source_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_get_synonym_map_request( # pylint: disable=name-too-long + synonym_map_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -134,9 +130,9 @@ def build_data_sources_get_request(data_source_name: str, **kwargs: Any) -> Http accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/datasources('{dataSourceName}')" + _url = "/synonymmaps('{synonymMapName}')" path_format_arguments = { - "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), + "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -150,7 +146,9 @@ def build_data_sources_get_request(data_source_name: str, **kwargs: Any) -> Http return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_data_sources_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_search_index_get_synonym_maps_request( # pylint: disable=name-too-long + *, select: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -158,7 +156,7 @@ def build_data_sources_list_request(*, select: Optional[str] = None, **kwargs: A accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/datasources" + _url = "/synonymmaps" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -171,7 +169,7 @@ def build_data_sources_list_request(*, select: Optional[str] = None, **kwargs: A return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_data_sources_create_request(**kwargs: Any) -> HttpRequest: +def build_search_index_create_synonym_map_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -180,7 +178,7 @@ def build_data_sources_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/datasources" + _url = "/synonymmaps" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -193,105 +191,14 @@ def build_data_sources_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexers_reset_request(indexer_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - # Construct URL - _url = "/indexers('{indexerName}')/search.reset" - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_indexers_resync_request(indexer_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - # Construct URL - _url = "/indexers('{indexerName}')/search.resync" - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_indexers_reset_docs_request( - indexer_name: str, *, overwrite: Optional[bool] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - # Construct URL - _url = "/indexers('{indexerName}')/search.resetdocs" - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if overwrite is not None: - _params["overwrite"] = _SERIALIZER.query("overwrite", overwrite, "bool") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_indexers_run_request(indexer_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - # Construct URL - _url = "/indexers('{indexerName}')/search.run" - path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_indexers_create_or_update_request( - indexer_name: str, +def build_search_index_create_or_update_index_request( # pylint: disable=name-too-long + index_name: str, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -302,26 +209,24 @@ def build_indexers_create_or_update_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexers('{indexerName}')" + _url = "/indexes('{indexName}')" path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - if disable_cache_reprocessing_change_detection is not None: - _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( - "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" - ) + if allow_index_downtime is not None: + _params["allowIndexDowntime"] = _SERIALIZER.query("allow_index_downtime", allow_index_downtime, "bool") # Construct headers _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -335,17 +240,22 @@ def build_indexers_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexers_delete_request( - indexer_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_index_delete_index_request( + index_name: str, + *, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/indexers('{indexerName}')" + _url = "/indexes('{indexName}')" path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -354,6 +264,10 @@ def build_indexers_delete_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -364,7 +278,9 @@ def build_indexers_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexers_get_request(indexer_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_get_index_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -372,9 +288,9 @@ def build_indexers_get_request(indexer_name: str, **kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexers('{indexerName}')" + _url = "/indexes('{indexName}')" path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -383,12 +299,16 @@ def build_indexers_get_request(indexer_name: str, **kwargs: Any) -> HttpRequest: _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexers_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_search_index_list_indexes_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -396,7 +316,7 @@ def build_indexers_list_request(*, select: Optional[str] = None, **kwargs: Any) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexers" + _url = "/indexes" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -409,7 +329,7 @@ def build_indexers_list_request(*, select: Optional[str] = None, **kwargs: Any) return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexers_create_request(**kwargs: Any) -> HttpRequest: +def build_search_index_create_index_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -418,7 +338,7 @@ def build_indexers_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexers" + _url = "/indexes" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -431,7 +351,9 @@ def build_indexers_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexers_get_status_request(indexer_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_get_index_statistics_request( # pylint: disable=name-too-long + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -439,9 +361,9 @@ def build_indexers_get_status_request(indexer_name: str, **kwargs: Any) -> HttpR accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexers('{indexerName}')/search.status" + _url = "/indexes('{indexName}')/search.stats" path_format_arguments = { - "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -450,46 +372,69 @@ def build_indexers_get_status_request(indexer_name: str, **kwargs: Any) -> HttpR _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" + ) _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_skillsets_create_or_update_request( - skillset_name: str, - *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any +def build_search_index_analyze_text_request( + index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skillsets('{skillsetName}')" + _url = "/indexes('{indexName}')/search.analyze" path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + "indexName": _SERIALIZER.url("index_name", index_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip_indexer_reset_requirement_for_cache is not None: - _params["ignoreResetRequirements"] = _SERIALIZER.query( - "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" - ) - if disable_cache_reprocessing_change_detection is not None: - _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( - "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + + # Construct headers + if query_source_authorization is not None: + _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( + "query_source_authorization", query_source_authorization, "str" ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_index_create_or_update_alias_request( # pylint: disable=name-too-long + alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/aliases('{aliasName}')" + path_format_arguments = { + "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") @@ -506,17 +451,17 @@ def build_skillsets_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_skillsets_delete_request( - skillset_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_index_delete_alias_request( + alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/skillsets('{skillsetName}')" + _url = "/aliases('{aliasName}')" path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -535,7 +480,7 @@ def build_skillsets_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_skillsets_get_request(skillset_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_get_alias_request(alias_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -543,9 +488,9 @@ def build_skillsets_get_request(skillset_name: str, **kwargs: Any) -> HttpReques accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skillsets('{skillsetName}')" + _url = "/aliases('{aliasName}')" path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -559,7 +504,7 @@ def build_skillsets_get_request(skillset_name: str, **kwargs: Any) -> HttpReques return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_skillsets_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_search_index_list_aliases_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -567,12 +512,10 @@ def build_skillsets_list_request(*, select: Optional[str] = None, **kwargs: Any) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skillsets" + _url = "/aliases" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -580,7 +523,7 @@ def build_skillsets_list_request(*, select: Optional[str] = None, **kwargs: Any) return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_skillsets_create_request(**kwargs: Any) -> HttpRequest: +def build_search_index_create_alias_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -589,7 +532,7 @@ def build_skillsets_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skillsets" + _url = "/aliases" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -602,16 +545,21 @@ def build_skillsets_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_skillsets_reset_skills_request(skillset_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_create_or_update_agent_request( # pylint: disable=name-too-long + agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "/skillsets('{skillsetName}')/search.resetskills" + _url = "/agents('{agentName}')" path_format_arguments = { - "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -620,40 +568,7 @@ def build_skillsets_reset_skills_request(skillset_name: str, **kwargs: Any) -> H _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_synonym_maps_create_or_update_request( # pylint: disable=name-too-long - synonym_map_name: str, - *, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - prefer: Literal["return=representation"] = kwargs.pop("prefer") - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/synonymmaps('{synonymMapName}')" - path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -667,21 +582,17 @@ def build_synonym_maps_create_or_update_request( # pylint: disable=name-too-lon return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_synonym_maps_delete_request( - synonym_map_name: str, - *, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any +def build_search_index_delete_agent_request( + agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/synonymmaps('{synonymMapName}')" + _url = "/agents('{agentName}')" path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), + "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -700,7 +611,7 @@ def build_synonym_maps_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_synonym_maps_get_request(synonym_map_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_get_agent_request(agent_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -708,9 +619,9 @@ def build_synonym_maps_get_request(synonym_map_name: str, **kwargs: Any) -> Http accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/synonymmaps('{synonymMapName}')" + _url = "/agents('{agentName}')" path_format_arguments = { - "synonymMapName": _SERIALIZER.url("synonym_map_name", synonym_map_name, "str"), + "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -724,7 +635,7 @@ def build_synonym_maps_get_request(synonym_map_name: str, **kwargs: Any) -> Http return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_synonym_maps_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_search_index_list_agents_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -732,12 +643,10 @@ def build_synonym_maps_list_request(*, select: Optional[str] = None, **kwargs: A accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/synonymmaps" + _url = "/agents" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -745,7 +654,7 @@ def build_synonym_maps_list_request(*, select: Optional[str] = None, **kwargs: A return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_synonym_maps_create_request(**kwargs: Any) -> HttpRequest: +def build_search_index_create_agent_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -754,7 +663,7 @@ def build_synonym_maps_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/synonymmaps" + _url = "/agents" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -767,14 +676,8 @@ def build_synonym_maps_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_create_or_update_request( - index_name: str, - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any +def build_search_index_create_or_update_knowledge_source_request( # pylint: disable=name-too-long + source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -785,24 +688,18 @@ def build_indexes_create_or_update_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexes('{indexName}')" + _url = "/knowledgesources('{sourceName}')" path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), + "sourceName": _SERIALIZER.url("source_name", source_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if allow_index_downtime is not None: - _params["allowIndexDowntime"] = _SERIALIZER.query("allow_index_downtime", allow_index_downtime, "bool") # Construct headers _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "query_source_authorization", query_source_authorization, "str" - ) if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -816,22 +713,17 @@ def build_indexes_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_delete_request( - index_name: str, - *, - query_source_authorization: Optional[str] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any +def build_search_index_delete_knowledge_source_request( # pylint: disable=name-too-long + source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/indexes('{indexName}')" + _url = "/knowledgesources('{sourceName}')" path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), + "sourceName": _SERIALIZER.url("source_name", source_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -840,10 +732,6 @@ def build_indexes_delete_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "query_source_authorization", query_source_authorization, "str" - ) if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -854,8 +742,8 @@ def build_indexes_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_get_request( - index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any +def build_search_index_get_knowledge_source_request( # pylint: disable=name-too-long + source_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -864,9 +752,9 @@ def build_indexes_get_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexes('{indexName}')" + _url = "/knowledgesources('{sourceName}')" path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), + "sourceName": _SERIALIZER.url("source_name", source_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -875,16 +763,12 @@ def build_indexes_get_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "query_source_authorization", query_source_authorization, "str" - ) _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_list_request(*, select: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_search_index_list_knowledge_sources_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -892,12 +776,10 @@ def build_indexes_list_request(*, select: Optional[str] = None, **kwargs: Any) - accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexes" + _url = "/knowledgesources" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if select is not None: - _params["$select"] = _SERIALIZER.query("select", select, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -905,7 +787,7 @@ def build_indexes_list_request(*, select: Optional[str] = None, **kwargs: Any) - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_create_request(**kwargs: Any) -> HttpRequest: +def build_search_index_create_knowledge_source_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -914,7 +796,7 @@ def build_indexes_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexes" + _url = "/knowledgesources" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -927,9 +809,7 @@ def build_indexes_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_get_statistics_request( - index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any -) -> HttpRequest: +def build_search_index_list_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -937,61 +817,43 @@ def build_indexes_get_statistics_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexes('{indexName}')/search.stats" - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/servicestats" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "query_source_authorization", query_source_authorization, "str" - ) _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_analyze_request( - index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any -) -> HttpRequest: +def build_search_index_get_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexes('{indexName}')/search.analyze" - path_format_arguments = { - "indexName": _SERIALIZER.url("index_name", index_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/indexstats" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if query_source_authorization is not None: - _headers["x-ms-query-source-authorization"] = _SERIALIZER.header( - "query_source_authorization", query_source_authorization, "str" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_aliases_create_or_update_request( - alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_indexer_create_or_update_data_source_connection_request( # pylint: disable=name-too-long + data_source_name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1002,15 +864,19 @@ def build_aliases_create_or_update_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/aliases('{aliasName}')" + _url = "/datasources('{dataSourceName}')" path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) # Construct headers _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") @@ -1027,17 +893,21 @@ def build_aliases_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_aliases_delete_request( - alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_indexer_delete_data_source_connection_request( # pylint: disable=name-too-long + data_source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/aliases('{aliasName}')" + _url = "/datasources('{dataSourceName}')" path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1056,7 +926,9 @@ def build_aliases_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_aliases_get_request(alias_name: str, **kwargs: Any) -> HttpRequest: +def build_search_indexer_get_data_source_connection_request( # pylint: disable=name-too-long + data_source_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1064,9 +936,9 @@ def build_aliases_get_request(alias_name: str, **kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/aliases('{aliasName}')" + _url = "/datasources('{dataSourceName}')" path_format_arguments = { - "aliasName": _SERIALIZER.url("alias_name", alias_name, "str"), + "dataSourceName": _SERIALIZER.url("data_source_name", data_source_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1080,7 +952,9 @@ def build_aliases_get_request(alias_name: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_aliases_list_request(**kwargs: Any) -> HttpRequest: +def build_search_indexer_get_data_source_connections_request( # pylint: disable=name-too-long + *, select: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1088,10 +962,12 @@ def build_aliases_list_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/aliases" + _url = "/datasources" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1099,7 +975,9 @@ def build_aliases_list_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_aliases_create_request(**kwargs: Any) -> HttpRequest: +def build_search_indexer_create_data_source_connection_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1108,7 +986,7 @@ def build_aliases_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/aliases" + _url = "/datasources" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -1121,21 +999,17 @@ def build_aliases_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_create_or_update_request( - agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_indexer_reset_indexer_request( # pylint: disable=name-too-long + indexer_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - # Construct URL - _url = "/agents('{agentName}')" + _url = "/indexers('{indexerName}')/search.reset" path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1144,31 +1018,19 @@ def build_agents_create_or_update_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - if_match = prep_if_match(etag, match_condition) - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if_none_match = prep_if_none_match(etag, match_condition) - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_delete_request( - agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any -) -> HttpRequest: +def build_search_indexer_resync_request(indexer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/agents('{agentName}')" + _url = "/indexers('{indexerName}')/search.resync" path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1177,83 +1039,67 @@ def build_agents_delete_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if_match = prep_if_match(etag, match_condition) - if if_match is not None: - _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - if_none_match = prep_if_none_match(etag, match_condition) - if if_none_match is not None: - _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_get_request(agent_name: str, **kwargs: Any) -> HttpRequest: +def build_search_indexer_reset_documents_request( # pylint: disable=name-too-long + indexer_name: str, *, overwrite: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - # Construct URL - _url = "/agents('{agentName}')" + _url = "/indexers('{indexerName}')/search.resetdocs" path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if overwrite is not None: + _params["overwrite"] = _SERIALIZER.query("overwrite", overwrite, "bool") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_list_request(**kwargs: Any) -> HttpRequest: +def build_search_indexer_run_indexer_request(indexer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") - # Construct URL - _url = "/agents" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_agents_create_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) - accept = _headers.pop("Accept", "application/json") + _url = "/indexers('{indexerName}')/search.run" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } - # Construct URL - _url = "/agents" + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_sources_create_or_update_request( - source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_indexer_create_or_update_request( # pylint: disable=name-too-long + indexer_name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1264,18 +1110,26 @@ def build_sources_create_or_update_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/knowledgesources('{sourceName}')" + _url = "/indexers('{indexerName}')" path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + if disable_cache_reprocessing_change_detection is not None: + _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( + "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + ) + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1289,17 +1143,17 @@ def build_sources_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_sources_delete_request( - source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_indexer_delete_indexer_request( # pylint: disable=name-too-long + indexer_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/knowledgesources('{sourceName}')" + _url = "/indexers('{indexerName}')" path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1318,7 +1172,7 @@ def build_sources_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_sources_get_request(source_name: str, **kwargs: Any) -> HttpRequest: +def build_search_indexer_get_indexer_request(indexer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1326,9 +1180,9 @@ def build_sources_get_request(source_name: str, **kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/knowledgesources('{sourceName}')" + _url = "/indexers('{indexerName}')" path_format_arguments = { - "sourceName": _SERIALIZER.url("source_name", source_name, "str"), + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1342,7 +1196,9 @@ def build_sources_get_request(source_name: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_sources_list_request(**kwargs: Any) -> HttpRequest: +def build_search_indexer_get_indexers_request( # pylint: disable=name-too-long + *, select: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1350,10 +1206,12 @@ def build_sources_list_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/knowledgesources" + _url = "/indexers" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1361,7 +1219,7 @@ def build_sources_list_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_sources_create_request(**kwargs: Any) -> HttpRequest: +def build_search_indexer_create_indexer_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1370,7 +1228,7 @@ def build_sources_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/knowledgesources" + _url = "/indexers" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -1383,7 +1241,9 @@ def build_sources_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_get_service_statistics_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_search_indexer_get_indexer_status_request( # pylint: disable=name-too-long + indexer_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1391,7 +1251,12 @@ def build_search_index_get_service_statistics_request(**kwargs: Any) -> HttpRequ accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/servicestats" + _url = "/indexers('{indexerName}')/search.status" + path_format_arguments = { + "indexerName": _SERIALIZER.url("indexer_name", indexer_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -1402,18 +1267,128 @@ def build_search_index_get_service_statistics_request(**kwargs: Any) -> HttpRequ return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_get_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_search_indexer_create_or_update_skillset_request( # pylint: disable=name-too-long + skillset_name: str, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/indexstats" + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_indexer_reset_requirement_for_cache is not None: + _params["ignoreResetRequirements"] = _SERIALIZER.query( + "skip_indexer_reset_requirement_for_cache", skip_indexer_reset_requirement_for_cache, "bool" + ) + if disable_cache_reprocessing_change_detection is not None: + _params["disableCacheReprocessingChangeDetection"] = _SERIALIZER.query( + "disable_cache_reprocessing_change_detection", disable_cache_reprocessing_change_detection, "bool" + ) + + # Construct headers + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_delete_skillset_request( # pylint: disable=name-too-long + skillset_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if_match = prep_if_match(etag, match_condition) + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_skillset_request( # pylint: disable=name-too-long + skillset_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets('{skillsetName}')" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_get_skillsets_request( # pylint: disable=name-too-long + *, select: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1421,44 +1396,75 @@ def build_search_index_get_index_stats_summary_request(**kwargs: Any) -> HttpReq return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class DataSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. +def build_search_indexer_create_skillset_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skillsets" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_search_indexer_reset_skills_request( # pylint: disable=name-too-long + skillset_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) + # Construct URL + _url = "/skillsets('{skillsetName}')/search.resetskills" + path_format_arguments = { + "skillsetName": _SERIALIZER.url("skillset_name", skillset_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`data_sources` attribute. - """ - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _SearchIndexClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchIndexClientConfiguration] +): @overload - def create_or_update( + def create_or_update_synonym_map( self, - data_source_name: str, - data_source: _models1.SearchIndexerDataSource, + synonym_map_name: str, + synonym_map: _models1.SynonymMap, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + **kwargs: Any, + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1467,32 +1473,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_synonym_map( self, - data_source_name: str, - data_source: JSON, + synonym_map_name: str, + synonym_map: JSON, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + **kwargs: Any, + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1501,32 +1503,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_synonym_map( self, - data_source_name: str, - data_source: IO[bytes], + synonym_map_name: str, + synonym_map: IO[bytes], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + **kwargs: Any, + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -1535,44 +1533,35 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) - def create_or_update( + def create_or_update_synonym_map( self, - data_source_name: str, - data_source: Union[_models1.SearchIndexerDataSource, JSON, IO[bytes]], + synonym_map_name: str, + synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + **kwargs: Any, + ) -> _models1.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Is one of the - following types: SearchIndexerDataSource, JSON, IO[bytes] Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or - IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Is one of the + following types: SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1594,18 +1583,17 @@ def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndexerDataSource] = kwargs.pop("cls", None) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map else: - _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_data_sources_create_or_update_request( - data_source_name=data_source_name, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + _request = build_search_index_create_or_update_synonym_map_request( + synonym_map_name=synonym_map_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -1640,7 +1628,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexerDataSource, response.json()) + deserialized = _deserialize(_models1.SynonymMap, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1648,18 +1636,18 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements + def delete_synonym_map( # pylint: disable=inconsistent-return-statements self, - data_source_name: str, + synonym_map_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> None: - """Deletes a datasource. + """Deletes a synonym map. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -1688,8 +1676,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_data_sources_delete_request( - data_source_name=data_source_name, + _request = build_search_index_delete_synonym_map_request( + synonym_map_name=synonym_map_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -1717,13 +1705,13 @@ def delete( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get(self, data_source_name: str, **kwargs: Any) -> _models1.SearchIndexerDataSource: - """Retrieves a datasource definition. + def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models1.SynonymMap: + """Retrieves a synonym map definition. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1737,10 +1725,10 @@ def get(self, data_source_name: str, **kwargs: Any) -> _models1.SearchIndexerDat _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.SearchIndexerDataSource] = kwargs.pop("cls", None) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) - _request = build_data_sources_get_request( - data_source_name=data_source_name, + _request = build_search_index_get_synonym_map_request( + synonym_map_name=synonym_map_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1770,7 +1758,7 @@ def get(self, data_source_name: str, **kwargs: Any) -> _models1.SearchIndexerDat if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexerDataSource, response.json()) + deserialized = _deserialize(_models1.SynonymMap, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1778,15 +1766,15 @@ def get(self, data_source_name: str, **kwargs: Any) -> _models1.SearchIndexerDat return deserialized # type: ignore @distributed_trace - def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListDataSourcesResult: - """Lists all datasources available for a search service. + def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSynonymMapsResult: + """Lists all synonym maps available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1800,9 +1788,9 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListD _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.ListDataSourcesResult] = kwargs.pop("cls", None) + cls: ClsType[_models1.ListSynonymMapsResult] = kwargs.pop("cls", None) - _request = build_data_sources_list_request( + _request = build_search_index_get_synonym_maps_request( select=select, api_version=self._config.api_version, headers=_headers, @@ -1833,7 +1821,7 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListD if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.ListDataSourcesResult, response.json()) + deserialized = _deserialize(_models1.ListSynonymMapsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1841,65 +1829,64 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListD return deserialized # type: ignore @overload - def create( - self, data_source: _models1.SearchIndexerDataSource, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource. + def create_synonym_map( + self, synonym_map: _models1.SynonymMap, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, data_source: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource. + def create_synonym_map( + self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Required. - :type data_source: JSON + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, data_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource. + def create_synonym_map( + self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Required. - :type data_source: IO[bytes] + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create( - self, data_source: Union[_models1.SearchIndexerDataSource, JSON, IO[bytes]], **kwargs: Any - ) -> _models1.SearchIndexerDataSource: - """Creates a new datasource. + def create_synonym_map( + self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Is one of the following types: - SearchIndexerDataSource, JSON, IO[bytes] Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or - IO[bytes] - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :param synonym_map: The definition of the synonym map to create. Is one of the following types: + SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1914,16 +1901,16 @@ def create( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndexerDataSource] = kwargs.pop("cls", None) + cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map else: - _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_data_sources_create_request( + _request = build_search_index_create_synonym_map_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -1955,57 +1942,567 @@ def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexerDataSource, response.json()) + deserialized = _deserialize(_models1.SynonymMap, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + def create_or_update_index( + self, + index_name: str, + index: _models1.SearchIndex, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. -class IndexersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`indexers` attribute. - """ + @overload + def create_or_update_index( + self, + index_name: str, + index: JSON, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: JSON + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ - @distributed_trace - def reset(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Resets the change tracking state associated with an indexer. + @overload + def create_or_update_index( + self, + index_name: str, + index: IO[bytes], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: None - :rtype: None + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + @distributed_trace + def create_or_update_index( + self, + index_name: str, + index: Union[_models1.SearchIndex, JSON, IO[bytes]], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndex: + """Creates a new search index or updates an index if it already exists. - _request = build_indexers_reset_request( - indexer_name=indexer_name, - api_version=self._config.api_version, + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_index_request( + index_name=index_name, + allow_index_downtime=allow_index_downtime, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_index( # pylint: disable=inconsistent-return-statements + self, + index_name: str, + *, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. This operation is permanent, with no + recovery option. Make sure you have a master copy of your index definition, data ingestion + code, and a backup of the primary data source in case you need to re-build the index. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_index_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_index( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models1.SearchIndex: + """Retrieves an index definition. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + _request = build_search_index_get_index_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_indexes(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SearchIndex"]: + """Lists all indexes available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: An iterator like instance of SearchIndex + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchIndex]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_indexes_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchIndex], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_index( + self, index: _models1.SearchIndex, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_index( + self, index: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_index( + self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_index(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_index_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -2014,34 +2511,48 @@ def reset(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=in } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndex, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Resync selective options from the datasource to be re-ingested by the indexer.". + def get_index_statistics( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models1.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: None - :rtype: None + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2055,10 +2566,11 @@ def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=i _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models1.GetIndexStatisticsResult] = kwargs.pop("cls", None) - _request = build_indexers_resync_request( - indexer_name=indexer_name, + _request = build_search_index_get_index_statistics_request( + index_name=index_name, + query_source_authorization=query_source_authorization, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2068,203 +2580,139 @@ def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=i } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.GetIndexStatisticsResult, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - def reset_docs( + def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[_models1.DocumentKeysOrIds] = None, + index_name: str, + request: _models1.AnalyzeTextOptions, *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + **kwargs: Any, + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeTextOptions + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def reset_docs( + def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[JSON] = None, + index_name: str, + request: JSON, *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + **kwargs: Any, + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Default value is None. - :type keys_or_ids: JSON - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def reset_docs( + def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[IO[bytes]] = None, + index_name: str, + request: IO[bytes], *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + **kwargs: Any, + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Default value is None. - :type keys_or_ids: IO[bytes] - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def reset_docs( # pylint: disable=inconsistent-return-statements + def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[Union[_models1.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + index_name: str, + request: Union[_models1.AnalyzeTextOptions, JSON, IO[bytes]], *, - overwrite: Optional[bool] = None, - **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, - IO[bytes] Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or - IO[bytes] - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if keys_or_ids else None - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" if keys_or_ids else None - _content = None - if isinstance(keys_or_ids, (IOBase, bytes)): - _content = keys_or_ids - else: - if keys_or_ids is not None: - _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - else: - _content = None - - _request = build_indexers_reset_docs_request( - indexer_name=indexer_name, - overwrite=overwrite, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def run(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Runs an indexer on-demand. + query_source_authorization: Optional[str] = None, + **kwargs: Any, + ) -> _models1.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: None - :rtype: None + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Is one of the following + types: AnalyzeTextOptions, JSON, IO[bytes] Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeTextOptions or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2275,14 +2723,25 @@ def run(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inco } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.AnalyzeResult] = kwargs.pop("cls", None) - _request = build_indexers_run_request( - indexer_name=indexer_name, + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_analyze_text_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -2291,46 +2750,50 @@ def run(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inco } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [202]: + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.AnalyzeResult, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - def create_or_update( + def create_or_update_alias( self, - indexer_name: str, - indexer: _models1.SearchIndexer, + alias_name: str, + alias: _models1.SearchAlias, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + **kwargs: Any, + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2339,36 +2802,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_alias( self, - indexer_name: str, - indexer: JSON, + alias_name: str, + alias: JSON, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + **kwargs: Any, + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2377,36 +2832,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_alias( self, - indexer_name: str, - indexer: IO[bytes], + alias_name: str, + alias: IO[bytes], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + **kwargs: Any, + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -2415,52 +2862,35 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) - def create_or_update( + def create_or_update_alias( self, - indexer_name: str, - indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], + alias_name: str, + alias: Union[_models1.SearchAlias, JSON, IO[bytes]], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + **kwargs: Any, + ) -> _models1.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Is one of the following - types: SearchIndexer, JSON, IO[bytes] Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2482,19 +2912,17 @@ def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer + if isinstance(alias, (IOBase, bytes)): + _content = alias else: - _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexers_create_or_update_request( - indexer_name=indexer_name, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + _request = build_search_index_create_or_update_alias_request( + alias_name=alias_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -2529,7 +2957,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexer, response.json()) + deserialized = _deserialize(_models1.SearchAlias, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2537,18 +2965,19 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements + def delete_alias( # pylint: disable=inconsistent-return-statements self, - indexer_name: str, + alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> None: - """Deletes an indexer. + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str + :param alias_name: The name of the alias. Required. + :type alias_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -2577,8 +3006,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_indexers_delete_request( - indexer_name=indexer_name, + _request = build_search_index_delete_alias_request( + alias_name=alias_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -2606,13 +3035,13 @@ def delete( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexer: - """Retrieves an indexer definition. + def get_alias(self, alias_name: str, **kwargs: Any) -> _models1.SearchAlias: + """Retrieves an alias definition. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :param alias_name: The name of the alias. Required. + :type alias_name: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2626,10 +3055,10 @@ def get(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexer: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) - _request = build_indexers_get_request( - indexer_name=indexer_name, + _request = build_search_index_get_alias_request( + alias_name=alias_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2659,7 +3088,7 @@ def get(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexer: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexer, response.json()) + deserialized = _deserialize(_models1.SearchAlias, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2667,17 +3096,18 @@ def get(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexer: return deserialized # type: ignore @distributed_trace - def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListIndexersResult: - """Lists all indexers available for a search service. + def list_aliases(self, **kwargs: Any) -> ItemPaged["_models1.SearchAlias"]: + """Lists all aliases available for a search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult + :return: An iterator like instance of SearchAlias + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchAlias]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2686,104 +3116,125 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListI } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListIndexersResult] = kwargs.pop("cls", None) + _request = build_search_index_list_aliases_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_indexers_list_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchAlias], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - response = pipeline_response.http_response + def get_next(next_link=None): + _request = prepare_request(next_link) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListIndexersResult, response.json()) + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return pipeline_response - return deserialized # type: ignore + return ItemPaged(get_next, extract_data) @overload - def create( - self, indexer: _models1.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexer: - """Creates a new indexer. + def create_alias( + self, alias: _models1.SearchAlias, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. - :param indexer: The definition of the indexer to create. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :param alias: The definition of the alias to create. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create(self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.SearchIndexer: - """Creates a new indexer. + def create_alias( + self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. - :param indexer: The definition of the indexer to create. Required. - :type indexer: JSON + :param alias: The definition of the alias to create. Required. + :type alias: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexer: - """Creates a new indexer. + def create_alias( + self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchAlias: + """Creates a new search alias. - :param indexer: The definition of the indexer to create. Required. - :type indexer: IO[bytes] + :param alias: The definition of the alias to create. Required. + :type alias: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create(self, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchIndexer: - """Creates a new indexer. + def create_alias(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchAlias: + """Creates a new search alias. - :param indexer: The definition of the indexer to create. Is one of the following types: - SearchIndexer, JSON, IO[bytes] Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :param alias: The definition of the alias to create. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2798,16 +3249,16 @@ def create(self, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], **kwar _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer + if isinstance(alias, (IOBase, bytes)): + _content = alias else: - _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexers_create_request( + _request = build_search_index_create_alias_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -2839,118 +3290,30 @@ def create(self, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], **kwar if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexer, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_status(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexerStatus: - """Returns the current status and execution history of an indexer. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models1.SearchIndexerStatus] = kwargs.pop("cls", None) - - _request = build_indexers_get_status_request( - indexer_name=indexer_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SearchIndexerStatus, response.json()) + deserialized = _deserialize(_models1.SearchAlias, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class SkillsetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`skillsets` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - def create_or_update( + def create_or_update_agent( self, - skillset_name: str, - skillset: _models1.SearchIndexerSkillset, + agent_name: str, + knowledge_agent: _models1.KnowledgeAgent, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2959,37 +3322,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_agent( self, - skillset_name: str, - skillset: JSON, + agent_name: str, + knowledge_agent: JSON, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2998,37 +3352,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_agent( self, - skillset_name: str, - skillset: IO[bytes], + agent_name: str, + knowledge_agent: IO[bytes], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + **kwargs: Any, + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -3037,53 +3382,36 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) - def create_or_update( + def create_or_update_agent( self, - skillset_name: str, - skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], + agent_name: str, + knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Is one of the + following types: KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3105,19 +3433,17 @@ def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent else: - _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_skillsets_create_or_update_request( - skillset_name=skillset_name, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + _request = build_search_index_create_or_update_agent_request( + agent_name=agent_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -3139,7 +3465,7 @@ def create_or_update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -3152,7 +3478,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3160,18 +3486,19 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements + def delete_agent( # pylint: disable=inconsistent-return-statements self, - skillset_name: str, + agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> None: - """Deletes a skillset in a search service. + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str + :param agent_name: The name of the agent. Required. + :type agent_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -3200,8 +3527,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_skillsets_delete_request( - skillset_name=skillset_name, + _request = build_search_index_delete_agent_request( + agent_name=agent_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -3229,13 +3556,13 @@ def delete( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get(self, skillset_name: str, **kwargs: Any) -> _models1.SearchIndexerSkillset: - """Retrieves a skillset in a search service. + def get_agent(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: + """Retrieves an agent definition. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :param agent_name: The name of the agent. Required. + :type agent_name: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3249,10 +3576,10 @@ def get(self, skillset_name: str, **kwargs: Any) -> _models1.SearchIndexerSkills _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) - _request = build_skillsets_get_request( - skillset_name=skillset_name, + _request = build_search_index_get_agent_request( + agent_name=agent_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3282,7 +3609,7 @@ def get(self, skillset_name: str, **kwargs: Any) -> _models1.SearchIndexerSkills if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3290,15 +3617,12 @@ def get(self, skillset_name: str, **kwargs: Any) -> _models1.SearchIndexerSkills return deserialized # type: ignore @distributed_trace - def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSkillsetsResult: - """List all skillsets in a search service. + def list_agents(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: + """Lists all agents available for a search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult + :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3312,10 +3636,9 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListS _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.ListSkillsetsResult] = kwargs.pop("cls", None) + cls: ClsType[_models1.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) - _request = build_skillsets_list_request( - select=select, + _request = build_search_index_list_agents_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -3345,132 +3668,7 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListS if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.ListSkillsetsResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create( - self, skillset: _models1.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. Is - one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or - IO[bytes] - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_skillsets_create_request( - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) + deserialized = _deserialize(_models1.ListKnowledgeAgentsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3478,85 +3676,65 @@ def create( return deserialized # type: ignore @overload - def reset_skills( - self, - skillset_name: str, - skill_names: _models1.SkillNames, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + def create_agent( + self, knowledge_agent: _models1.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ - @overload - def reset_skills( - self, skillset_name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + @overload + def create_agent( + self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Required. - :type skill_names: JSON + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def reset_skills( - self, skillset_name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + def create_agent( + self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Required. - :type skill_names: IO[bytes] + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def reset_skills( # pylint: disable=inconsistent-return-statements - self, skillset_name: str, skill_names: Union[_models1.SkillNames, JSON, IO[bytes]], **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + def create_agent( + self, knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] - :return: None - :rtype: None + :param knowledge_agent: The definition of the agent to create. Is one of the following types: + KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or + IO[bytes] + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3571,17 +3749,16 @@ def reset_skills( # pylint: disable=inconsistent-return-statements _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(skill_names, (IOBase, bytes)): - _content = skill_names + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent else: - _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_skillsets_reset_skills_request( - skillset_name=skillset_name, + _request = build_search_index_create_agent_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -3593,56 +3770,50 @@ def reset_skills( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class SynonymMapsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`synonym_maps` attribute. - """ + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + return deserialized # type: ignore @overload - def create_or_update( + def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: _models1.SynonymMap, + source_name: str, + knowledge_source: _models1.KnowledgeSource, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3651,28 +3822,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: JSON, + source_name: str, + knowledge_source: JSON, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: JSON + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3681,28 +3852,28 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: IO[bytes], + source_name: str, + knowledge_source: IO[bytes], *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -3711,35 +3882,36 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_or_update( + def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], + source_name: str, + knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + **kwargs: Any, + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Is one of the - following types: SynonymMap, JSON, IO[bytes] Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Is one of + the following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3761,17 +3933,17 @@ def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source else: - _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_synonym_maps_create_or_update_request( - synonym_map_name=synonym_map_name, + _request = build_search_index_create_or_update_knowledge_source_request( + source_name=source_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -3806,7 +3978,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SynonymMap, response.json()) + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3814,18 +3986,18 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements + def delete_knowledge_source( # pylint: disable=inconsistent-return-statements self, - synonym_map_name: str, + source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> None: - """Deletes a synonym map. + """Deletes an existing knowledge source. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str + :param source_name: The name of the knowledge source. Required. + :type source_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -3854,8 +4026,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_synonym_maps_delete_request( - synonym_map_name=synonym_map_name, + _request = build_search_index_delete_knowledge_source_request( + source_name=source_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -3879,80 +4051,17 @@ def delete( # pylint: disable=inconsistent-return-statements error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get(self, synonym_map_name: str, **kwargs: Any) -> _models1.SynonymMap: - """Retrieves a synonym map definition. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) - - _request = build_synonym_maps_get_request( - synonym_map_name=synonym_map_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SynonymMap, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSynonymMapsResult: - """Lists all synonym maps available for a search service. + def get_knowledge_source(self, source_name: str, **kwargs: Any) -> _models1.KnowledgeSource: + """Retrieves a knowledge source definition. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3966,10 +4075,10 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListS _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.ListSynonymMapsResult] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) - _request = build_synonym_maps_list_request( - select=select, + _request = build_search_index_get_knowledge_source_request( + source_name=source_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3999,70 +4108,20 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListS if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.ListSynonymMapsResult, response.json()) + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def create( - self, synonym_map: _models1.SynonymMap, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map. - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map. - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SynonymMap: - """Creates a new synonym map. - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace - def create(self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwargs: Any) -> _models1.SynonymMap: - """Creates a new synonym map. + def list_knowledge_sources(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: + """Lists all knowledge sources available for a search service. - :param synonym_map: The definition of the synonym map to create. Is one of the following types: - SynonymMap, JSON, IO[bytes] Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4073,23 +4132,13 @@ def create(self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwa } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models1.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - _request = build_synonym_maps_create_request( - content_type=content_type, + _request = build_search_index_list_knowledge_sources_request( api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -4105,7 +4154,7 @@ def create(self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwa response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -4118,193 +4167,73 @@ def create(self, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], **kwa if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SynonymMap, response.json()) + deserialized = _deserialize(_models1.ListKnowledgeSourcesResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`indexes` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - def create_or_update( - self, - index_name: str, - index: _models1.SearchIndex, - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. + def create_knowledge_source( + self, knowledge_source: _models1.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( - self, - index_name: str, - index: JSON, - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. + def create_knowledge_source( + self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: JSON - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( - self, - index_name: str, - index: IO[bytes], - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. + def create_knowledge_source( + self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - index_name: str, - index: Union[_models1.SearchIndex, JSON, IO[bytes]], - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Is one of the following types: - SearchIndex, JSON, IO[bytes] Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_knowledge_source( + self, knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Is one of the + following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4313,35 +4242,22 @@ def create_or_update( 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(index, (IOBase, bytes)): - _content = index + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source else: - _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexes_create_or_update_request( - index_name=index_name, - allow_index_downtime=allow_index_downtime, - query_source_authorization=query_source_authorization, - etag=etag, - match_condition=match_condition, - prefer=prefer, + _request = build_search_index_create_knowledge_source_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -4360,7 +4276,7 @@ def create_or_update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -4373,7 +4289,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndex, response.json()) + deserialized = _deserialize(_models1.KnowledgeSource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -4381,96 +4297,11 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - index_name: str, - *, - query_source_authorization: Optional[str] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. This operation is permanent, with no - recovery option. Make sure you have a master copy of your index definition, data ingestion - code, and a backup of the primary data source in case you need to re-build the index. - - :param index_name: The name of the index. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_indexes_delete_request( - index_name=index_name, - query_source_authorization=query_source_authorization, - etag=etag, - match_condition=match_condition, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models1.SearchIndex: - """Retrieves an index definition. + def list_index_stats_summary(self, **kwargs: Any) -> _models1.SearchServiceStatistics: + """Gets service level statistics for a search service. - :param index_name: The name of the index. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4484,11 +4315,9 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchServiceStatistics] = kwargs.pop("cls", None) - _request = build_indexes_get_request( - index_name=index_name, - query_source_authorization=query_source_authorization, + _request = build_search_index_list_index_stats_summary_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -4518,7 +4347,7 @@ def get( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndex, response.json()) + deserialized = _deserialize(_models1.SearchServiceStatistics, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -4526,21 +4355,23 @@ def get( return deserialized # type: ignore @distributed_trace - def list(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SearchIndex"]: - """Lists all indexes available for a search service. + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: + """Retrieves a summary of statistics for all indexes in the search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: An iterator like instance of SearchIndex - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :return: An iterator like instance of IndexStatisticsSummary + :rtype: + ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models1.SearchIndex]] = kwargs.pop("cls", None) + cls: ClsType[list[_models1.IndexStatisticsSummary]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -4553,8 +4384,7 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_mo def prepare_request(next_link=None): if not next_link: - _request = build_indexes_list_request( - select=select, + _request = build_search_index_get_index_stats_summary_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -4590,7 +4420,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models1.SearchIndex], deserialized.get("value", [])) + list_of_elem = _deserialize(list[_models1.IndexStatisticsSummary], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return None, iter(list_of_elem) @@ -4613,61 +4443,150 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) + +class _SearchIndexerClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchIndexerClientConfiguration] +): + @overload - def create( - self, index: _models1.SearchIndex, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndex: - """Creates a new search index. + def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: _models1.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create(self, index: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.SearchIndex: - """Creates a new search index. + def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Required. - :type index: JSON + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchIndex: - """Creates a new search index. + def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Required. - :type index: IO[bytes] + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchIndex: - """Creates a new search index. + @api_version_validation( + params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: Union[_models1.SearchIndexerDataSourceConnection, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Is one of the following types: - SearchIndex, JSON, IO[bytes] Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Is one of the + following types: SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or + JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4676,22 +4595,34 @@ def create(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} + prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(index, (IOBase, bytes)): - _content = index + if isinstance(data_source, (IOBase, bytes)): + _content = data_source else: - _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexes_create_request( + _request = build_search_indexer_create_or_update_data_source_connection_request( + data_source_name=data_source_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + etag=etag, + match_condition=match_condition, + prefer=prefer, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -4710,7 +4641,7 @@ def create(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -4723,7 +4654,7 @@ def create(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchIndex, response.json()) + deserialized = _deserialize(_models1.SearchIndexerDataSourceConnection, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -4731,20 +4662,25 @@ def create(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kwargs: return deserialized # type: ignore @distributed_trace - def get_statistics( - self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models1.GetIndexStatisticsResult: - """Returns statistics for the given index, including a document count and storage usage. + def delete_data_source_connection( # pylint: disable=inconsistent-return-statements + self, + data_source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, + ) -> None: + """Deletes a datasource. - :param index_name: The name of the index. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. - :paramtype query_source_authorization: str - :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4753,16 +4689,75 @@ def get_statistics( 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.GetIndexStatisticsResult] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_indexes_get_statistics_request( - index_name=index_name, - query_source_authorization=query_source_authorization, + _request = build_search_indexer_delete_data_source_connection_request( + data_source_name=data_source_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_data_source_connection( + self, data_source_name: str, **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Retrieves a datasource definition. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_data_source_connection_request( + data_source_name=data_source_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4792,119 +4787,25 @@ def get_statistics( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.GetIndexStatisticsResult, response.json()) + deserialized = _deserialize(_models1.SearchIndexerDataSourceConnection, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def analyze( - self, - index_name: str, - request: _models1.AnalyzeRequest, - *, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models1.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def analyze( - self, - index_name: str, - request: JSON, - *, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models1.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def analyze( - self, - index_name: str, - request: IO[bytes], - *, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models1.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace - def analyze( - self, - index_name: str, - request: Union[_models1.AnalyzeRequest, JSON, IO[bytes]], - *, - query_source_authorization: Optional[str] = None, - **kwargs: Any - ) -> _models1.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. + def get_data_source_connections( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> _models1.ListDataSourcesResult: + """Lists all datasources available for a search service. - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Is one of the following - types: AnalyzeRequest, JSON, IO[bytes] Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or JSON or IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4915,25 +4816,14 @@ def analyze( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.AnalyzeResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(request, (IOBase, bytes)): - _content = request - else: - _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models1.ListDataSourcesResult] = kwargs.pop("cls", None) - _request = build_indexes_analyze_request( - index_name=index_name, - query_source_authorization=query_source_authorization, - content_type=content_type, + _request = build_search_indexer_get_data_source_connections_request( + select=select, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -4962,161 +4852,81 @@ def analyze( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.AnalyzeResult, response.json()) + deserialized = _deserialize(_models1.ListDataSourcesResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class AliasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`aliases` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - def create_or_update( + def create_data_source_connection( self, - alias_name: str, - alias: _models1.SearchAlias, + data_source: _models1.SearchIndexerDataSourceConnection, *, content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias + :param data_source: The definition of the datasource to create. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( - self, - alias_name: str, - alias: JSON, - *, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + def create_data_source_connection( + self, data_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: JSON + :param data_source: The definition of the datasource to create. Required. + :type data_source: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( - self, - alias_name: str, - alias: IO[bytes], - *, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + def create_data_source_connection( + self, data_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] + :param data_source: The definition of the datasource to create. Required. + :type data_source: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": [ - "api_version", - "prefer", - "client_request_id", - "alias_name", - "content_type", - "accept", - "etag", - "match_condition", - ] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def create_or_update( - self, - alias_name: str, - alias: Union[_models1.SearchAlias, JSON, IO[bytes]], - *, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + def create_data_source_connection( + self, data_source: Union[_models1.SearchIndexerDataSourceConnection, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Is one of the following types: - SearchAlias, JSON, IO[bytes] Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :param data_source: The definition of the datasource to create. Is one of the following types: + SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or + JSON or IO[bytes] + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5125,33 +4935,22 @@ def create_or_update( 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias + if isinstance(data_source, (IOBase, bytes)): + _content = data_source else: - _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_aliases_create_or_update_request( - alias_name=alias_name, - etag=etag, - match_condition=match_condition, - prefer=prefer, + _request = build_search_indexer_create_data_source_connection_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -5170,7 +4969,7 @@ def create_or_update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -5183,7 +4982,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SearchAlias, response.json()) + deserialized = _deserialize(_models1.SearchIndexerDataSourceConnection, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5191,31 +4990,11 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "etag", "match_condition"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def delete( # pylint: disable=inconsistent-return-statements - self, - alias_name: str, - *, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. + def reset_indexer(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Resets the change tracking state associated with an indexer. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5226,12 +5005,6 @@ def delete( # pylint: disable=inconsistent-return-statements 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} @@ -5239,10 +5012,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_aliases_delete_request( - alias_name=alias_name, - etag=etag, - match_condition=match_condition, + _request = build_search_indexer_reset_indexer_request( + indexer_name=indexer_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5259,7 +5030,7 @@ def delete( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [204, 404]: + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) @@ -5270,16 +5041,16 @@ def delete( # pylint: disable=inconsistent-return-statements @distributed_trace @api_version_validation( method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "accept"]}, + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], ) - def get(self, alias_name: str, **kwargs: Any) -> _models1.SearchAlias: - """Retrieves an alias definition. + def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Resync selective options from the datasource to be re-ingested by the indexer.". - :param alias_name: The name of the alias. Required. - :type alias_name: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5293,194 +5064,152 @@ def get(self, alias_name: str, **kwargs: Any) -> _models1.SearchAlias: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_aliases_get_request( - alias_name=alias_name, + _request = build_search_indexer_resync_request( + indexer_name=indexer_name, api_version=self._config.api_version, headers=_headers, params=_params, ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SearchAlias, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def list(self, **kwargs: Any) -> ItemPaged["_models1.SearchAlias"]: - """Lists all aliases available for a search service. - - :return: An iterator like instance of SearchAlias - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models1.SearchAlias]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_aliases_list_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models1.SearchAlias], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + response = pipeline_response.http_response - return pipeline_response + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return ItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, None, {}) # type: ignore @overload - def create( - self, alias: _models1.SearchAlias, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchAlias: - """Creates a new search alias. + def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[_models1.DocumentKeysOrIds] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create(self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.SearchAlias: - """Creates a new search alias. + def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[JSON] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Required. - :type alias: JSON + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: JSON + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchAlias: - """Creates a new search alias. + def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[IO[bytes]] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Required. - :type alias: IO[bytes] + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace @api_version_validation( method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + params_added_on={ + "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] + }, api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], ) - def create(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kwargs: Any) -> _models1.SearchAlias: - """Creates a new search alias. + def reset_documents( # pylint: disable=inconsistent-return-statements + self, + indexer_name: str, + keys_or_ids: Optional[Union[_models1.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + *, + overwrite: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Is one of the following types: - SearchAlias, JSON, IO[bytes] Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, + IO[bytes] Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or + IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5495,16 +5224,22 @@ def create(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kwargs: _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) + content_type = content_type if keys_or_ids else None + cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/json" + content_type = content_type or "application/json" if keys_or_ids else None _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias + if isinstance(keys_or_ids, (IOBase, bytes)): + _content = keys_or_ids else: - _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if keys_or_ids is not None: + _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + else: + _content = None - _request = build_aliases_create_request( + _request = build_search_indexer_reset_documents_request( + indexer_name=indexer_name, + overwrite=overwrite, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -5516,68 +5251,95 @@ def create(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kwargs: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SearchAlias, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore - return deserialized # type: ignore + @distributed_trace + def run_indexer(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Runs an indexer on-demand. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_run_indexer_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) -class AgentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + response = pipeline_response.http_response - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`agents` attribute. - """ + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + if cls: + return cls(pipeline_response, None, {}) # type: ignore @overload def create_or_update( self, - agent_name: str, - knowledge_agent: _models1.KnowledgeAgent, + indexer_name: str, + indexer: _models1.SearchIndexer, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5586,28 +5348,36 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create_or_update( self, - agent_name: str, - knowledge_agent: JSON, + indexer_name: str, + indexer: JSON, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: JSON + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5616,28 +5386,36 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create_or_update( self, - agent_name: str, - knowledge_agent: IO[bytes], + indexer_name: str, + indexer: IO[bytes], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: IO[bytes] + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -5646,52 +5424,52 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace @api_version_validation( - method_added_on="2025-08-01-preview", params_added_on={ "2025-08-01-preview": [ - "api_version", - "prefer", - "client_request_id", - "agent_name", - "content_type", - "accept", - "etag", - "match_condition", + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", ] }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) def create_or_update( self, - agent_name: str, - knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], + indexer_name: str, + indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Is one of the - following types: KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Is one of the following + types: SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5713,17 +5491,19 @@ def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent + if isinstance(indexer, (IOBase, bytes)): + _content = indexer else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_create_or_update_request( - agent_name=agent_name, + _request = build_search_indexer_create_or_update_request( + indexer_name=indexer_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, etag=etag, match_condition=match_condition, prefer=prefer, @@ -5745,7 +5525,7 @@ def create_or_update( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -5758,7 +5538,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models1.SearchIndexer, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5766,26 +5546,18 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "etag", "match_condition"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def delete( # pylint: disable=inconsistent-return-statements + def delete_indexer( # pylint: disable=inconsistent-return-statements self, - agent_name: str, + indexer_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. + """Deletes an indexer. - :param agent_name: The name of the agent. Required. - :type agent_name: str + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -5814,8 +5586,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_agents_delete_request( - agent_name=agent_name, + _request = build_search_indexer_delete_indexer_request( + indexer_name=indexer_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -5843,18 +5615,13 @@ def delete( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def get(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: - """Retrieves an agent definition. + def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexer: + """Retrieves an indexer definition. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5868,10 +5635,10 @@ def get(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) - _request = build_agents_get_request( - agent_name=agent_name, + _request = build_search_indexer_get_indexer_request( + indexer_name=indexer_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5901,7 +5668,7 @@ def get(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models1.SearchIndexer, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5909,17 +5676,15 @@ def get(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def list(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: - """Lists all agents available for a search service. + def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListIndexersResult: + """Lists all indexers available for a search service. - :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListIndexersResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5933,9 +5698,10 @@ def list(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) + cls: ClsType[_models1.ListIndexersResult] = kwargs.pop("cls", None) - _request = build_agents_list_request( + _request = build_search_indexer_get_indexers_request( + select=select, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5965,7 +5731,7 @@ def list(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.ListKnowledgeAgentsResult, response.json()) + deserialized = _deserialize(_models1.ListIndexersResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5973,70 +5739,134 @@ def list(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: return deserialized # type: ignore @overload - def create( - self, knowledge_agent: _models1.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_indexer( + self, indexer: _models1.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer: The definition of the indexer to create. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_indexer( + self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: JSON + :param indexer: The definition of the indexer to create. Required. + :type indexer: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_indexer( + self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: IO[bytes] + :param indexer: The definition of the indexer to create. Required. + :type indexer: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def create( - self, knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_indexer( + self, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Is one of the following types: + SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_indexer_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models1.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - :param knowledge_agent: The definition of the agent to create. Is one of the following types: - KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + return deserialized # type: ignore + + @distributed_trace + def get_indexer_status(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexerStatus: + """Returns the current status and execution history of an indexer. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6047,23 +5877,14 @@ def create( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent - else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models1.SearchIndexerStatus] = kwargs.pop("cls", None) - _request = build_agents_create_request( - content_type=content_type, + _request = build_search_indexer_get_indexer_status_request( + indexer_name=indexer_name, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -6079,7 +5900,7 @@ def create( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -6092,48 +5913,39 @@ def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models1.SearchIndexerStatus, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class SourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.SearchIndexClient`'s - :attr:`sources` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - def create_or_update( + def create_or_update_skillset( self, - source_name: str, - knowledge_source: _models1.KnowledgeSource, + skillset_name: str, + skillset: _models1.SearchIndexerSkillset, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6142,28 +5954,37 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_skillset( self, - source_name: str, - knowledge_source: JSON, + skillset_name: str, + skillset: JSON, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: JSON + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6172,28 +5993,37 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update( + def create_or_update_skillset( self, - source_name: str, - knowledge_source: IO[bytes], + skillset_name: str, + skillset: IO[bytes], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -6202,52 +6032,53 @@ def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace @api_version_validation( - method_added_on="2025-08-01-preview", params_added_on={ "2025-08-01-preview": [ - "api_version", - "prefer", - "client_request_id", - "source_name", - "content_type", - "accept", - "etag", - "match_condition", + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", ] }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - def create_or_update( + def create_or_update_skillset( self, - source_name: str, - knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], + skillset_name: str, + skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + **kwargs: Any, + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Is one of - the following types: KnowledgeSource, JSON, IO[bytes] Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6269,17 +6100,19 @@ def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source + if isinstance(skillset, (IOBase, bytes)): + _content = skillset else: - _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_sources_create_or_update_request( - source_name=source_name, + _request = build_search_indexer_create_or_update_skillset_request( + skillset_name=skillset_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, etag=etag, match_condition=match_condition, prefer=prefer, @@ -6314,7 +6147,7 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6322,25 +6155,18 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "client_request_id", "source_name", "etag", "match_condition"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def delete( # pylint: disable=inconsistent-return-statements + def delete_skillset( # pylint: disable=inconsistent-return-statements self, - source_name: str, + skillset_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any + **kwargs: Any, ) -> None: - """Deletes an existing knowledge source. + """Deletes a skillset in a search service. - :param source_name: The name of the knowledge source. Required. - :type source_name: str + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -6369,8 +6195,8 @@ def delete( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_sources_delete_request( - source_name=source_name, + _request = build_search_indexer_delete_skillset_request( + skillset_name=skillset_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -6398,18 +6224,13 @@ def delete( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "source_name", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def get(self, source_name: str, **kwargs: Any) -> _models1.KnowledgeSource: - """Retrieves a knowledge source definition. + def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models1.SearchIndexerSkillset: + """Retrieves a skillset in a search service. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6423,10 +6244,10 @@ def get(self, source_name: str, **kwargs: Any) -> _models1.KnowledgeSource: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) - _request = build_sources_get_request( - source_name=source_name, + _request = build_search_indexer_get_skillset_request( + skillset_name=skillset_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6456,7 +6277,7 @@ def get(self, source_name: str, **kwargs: Any) -> _models1.KnowledgeSource: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6464,17 +6285,15 @@ def get(self, source_name: str, **kwargs: Any) -> _models1.KnowledgeSource: return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def list(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: - """Lists all knowledge sources available for a search service. + def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSkillsetsResult: + """List all skillsets in a search service. - :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6488,9 +6307,10 @@ def list(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) + cls: ClsType[_models1.ListSkillsetsResult] = kwargs.pop("cls", None) - _request = build_sources_list_request( + _request = build_search_indexer_get_skillsets_request( + select=select, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6520,7 +6340,7 @@ def list(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.ListKnowledgeSourcesResult, response.json()) + deserialized = _deserialize(_models1.ListSkillsetsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6528,70 +6348,68 @@ def list(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: return deserialized # type: ignore @overload - def create( - self, knowledge_source: _models1.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source. + def create_skillset( + self, skillset: _models1.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source. + def create_skillset( + self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: JSON + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source. + def create_skillset( + self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: IO[bytes] + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def create( - self, knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source. + def create_skillset( + self, skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Is one of the - following types: KnowledgeSource, JSON, IO[bytes] Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + :param skillset: The skillset containing one or more skills to create in a search service. Is + one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or IO[bytes] - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6606,16 +6424,16 @@ def create( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) + cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source + if isinstance(skillset, (IOBase, bytes)): + _content = skillset else: - _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_sources_create_request( + _request = build_search_indexer_create_skillset_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6647,24 +6465,93 @@ def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeSource, response.json()) + deserialized = _deserialize(_models1.SearchIndexerSkillset, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + def reset_skills( + self, + skillset_name: str, + skill_names: _models1.SkillNames, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ -class _SearchIndexClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchIndexClientConfiguration] -): + @overload + def reset_skills( + self, skillset_name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def reset_skills( + self, skillset_name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatistics: - """Gets service level statistics for a search service. + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def reset_skills( # pylint: disable=inconsistent-return-statements + self, skillset_name: str, skill_names: Union[_models1.SkillNames, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. - :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6675,13 +6562,24 @@ def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatist } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.SearchServiceStatistics] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skill_names, (IOBase, bytes)): + _content = skill_names + else: + _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_get_service_statistics_request( + _request = build_search_indexer_reset_skills_request( + skillset_name=skillset_name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -6690,118 +6588,17 @@ def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatist } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models2.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SearchServiceStatistics, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def get_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: - """Retrieves a summary of statistics for all indexes in the search service. - - :return: An iterator like instance of IndexStatisticsSummary - :rtype: - ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models1.IndexStatisticsSummary]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_index_get_index_stats_summary_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models1.IndexStatisticsSummary], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py index a5266d617dfe..7e8a8679322d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/__init__.py @@ -13,6 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._client import SearchIndexClient # type: ignore +from ._client import SearchIndexerClient # type: ignore try: from ._patch import __all__ as _patch_all @@ -23,6 +24,7 @@ __all__ = [ "SearchIndexClient", + "SearchIndexerClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py index 52a887802d62..8827716ecdcf 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_client.py @@ -16,42 +16,16 @@ from azure.core.rest import AsyncHttpResponse, HttpRequest from ..._utils.serialization import Deserializer, Serializer -from ._configuration import SearchIndexClientConfiguration -from .operations import ( - AgentsOperations, - AliasesOperations, - DataSourcesOperations, - IndexersOperations, - IndexesOperations, - SkillsetsOperations, - SourcesOperations, - SynonymMapsOperations, - _SearchIndexClientOperationsMixin, -) +from ._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration +from ._operations import _SearchIndexClientOperationsMixin, _SearchIndexerClientOperationsMixin if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class SearchIndexClient(_SearchIndexClientOperationsMixin): # pylint: disable=too-many-instance-attributes +class SearchIndexClient(_SearchIndexClientOperationsMixin): """SearchIndexClient. - :ivar data_sources: DataSourcesOperations operations - :vartype data_sources: azure.search.documents.aio.operations.DataSourcesOperations - :ivar indexers: IndexersOperations operations - :vartype indexers: azure.search.documents.aio.operations.IndexersOperations - :ivar skillsets: SkillsetsOperations operations - :vartype skillsets: azure.search.documents.aio.operations.SkillsetsOperations - :ivar synonym_maps: SynonymMapsOperations operations - :vartype synonym_maps: azure.search.documents.aio.operations.SynonymMapsOperations - :ivar indexes: IndexesOperations operations - :vartype indexes: azure.search.documents.aio.operations.IndexesOperations - :ivar aliases: AliasesOperations operations - :vartype aliases: azure.search.documents.aio.operations.AliasesOperations - :ivar agents: AgentsOperations operations - :vartype agents: azure.search.documents.aio.operations.AgentsOperations - :ivar sources: SourcesOperations operations - :vartype sources: azure.search.documents.aio.operations.SourcesOperations :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -92,14 +66,89 @@ def __init__( self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.data_sources = DataSourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexers = IndexersOperations(self._client, self._config, self._serialize, self._deserialize) - self.skillsets = SkillsetsOperations(self._client, self._config, self._serialize, self._deserialize) - self.synonym_maps = SynonymMapsOperations(self._client, self._config, self._serialize, self._deserialize) - self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) - self.aliases = AliasesOperations(self._client, self._config, self._serialize, self._deserialize) - self.agents = AgentsOperations(self._client, self._config, self._serialize, self._deserialize) - self.sources = SourcesOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) + + +class SearchIndexerClient(_SearchIndexerClientOperationsMixin): + """SearchIndexerClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = SearchIndexerClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py index a511669d940d..c50be6dff29a 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_configuration.py @@ -72,3 +72,60 @@ def _configure(self, **kwargs: Any) -> None: self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = self._infer_policy(**kwargs) + + +class SearchIndexerClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for SearchIndexerClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-11-01-preview") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://search.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "search-documents/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py new file mode 100644 index 000000000000..baa9bb7fd3fa --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _SearchIndexerClientOperationsMixin # type: ignore # pylint: disable=unused-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py similarity index 89% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 15073ee0c257..1033ec6e37de 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -34,107 +34,88 @@ from ... import models as _models2 from .... import models as _models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize -from ...._utils.serialization import Deserializer, Serializer from ...._utils.utils import ClientMixinABC from ...._validation import api_version_validation -from ...operations._operations import ( - build_agents_create_or_update_request, - build_agents_create_request, - build_agents_delete_request, - build_agents_get_request, - build_agents_list_request, - build_aliases_create_or_update_request, - build_aliases_create_request, - build_aliases_delete_request, - build_aliases_get_request, - build_aliases_list_request, - build_data_sources_create_or_update_request, - build_data_sources_create_request, - build_data_sources_delete_request, - build_data_sources_get_request, - build_data_sources_list_request, - build_indexers_create_or_update_request, - build_indexers_create_request, - build_indexers_delete_request, - build_indexers_get_request, - build_indexers_get_status_request, - build_indexers_list_request, - build_indexers_reset_docs_request, - build_indexers_reset_request, - build_indexers_resync_request, - build_indexers_run_request, - build_indexes_analyze_request, - build_indexes_create_or_update_request, - build_indexes_create_request, - build_indexes_delete_request, - build_indexes_get_request, - build_indexes_get_statistics_request, - build_indexes_list_request, +from ..._operations._operations import ( + build_search_index_analyze_text_request, + build_search_index_create_agent_request, + build_search_index_create_alias_request, + build_search_index_create_index_request, + build_search_index_create_knowledge_source_request, + build_search_index_create_or_update_agent_request, + build_search_index_create_or_update_alias_request, + build_search_index_create_or_update_index_request, + build_search_index_create_or_update_knowledge_source_request, + build_search_index_create_or_update_synonym_map_request, + build_search_index_create_synonym_map_request, + build_search_index_delete_agent_request, + build_search_index_delete_alias_request, + build_search_index_delete_index_request, + build_search_index_delete_knowledge_source_request, + build_search_index_delete_synonym_map_request, + build_search_index_get_agent_request, + build_search_index_get_alias_request, + build_search_index_get_index_request, + build_search_index_get_index_statistics_request, build_search_index_get_index_stats_summary_request, - build_search_index_get_service_statistics_request, - build_skillsets_create_or_update_request, - build_skillsets_create_request, - build_skillsets_delete_request, - build_skillsets_get_request, - build_skillsets_list_request, - build_skillsets_reset_skills_request, - build_sources_create_or_update_request, - build_sources_create_request, - build_sources_delete_request, - build_sources_get_request, - build_sources_list_request, - build_synonym_maps_create_or_update_request, - build_synonym_maps_create_request, - build_synonym_maps_delete_request, - build_synonym_maps_get_request, - build_synonym_maps_list_request, + build_search_index_get_knowledge_source_request, + build_search_index_get_synonym_map_request, + build_search_index_get_synonym_maps_request, + build_search_index_list_agents_request, + build_search_index_list_aliases_request, + build_search_index_list_index_stats_summary_request, + build_search_index_list_indexes_request, + build_search_index_list_knowledge_sources_request, + build_search_indexer_create_data_source_connection_request, + build_search_indexer_create_indexer_request, + build_search_indexer_create_or_update_data_source_connection_request, + build_search_indexer_create_or_update_request, + build_search_indexer_create_or_update_skillset_request, + build_search_indexer_create_skillset_request, + build_search_indexer_delete_data_source_connection_request, + build_search_indexer_delete_indexer_request, + build_search_indexer_delete_skillset_request, + build_search_indexer_get_data_source_connection_request, + build_search_indexer_get_data_source_connections_request, + build_search_indexer_get_indexer_request, + build_search_indexer_get_indexer_status_request, + build_search_indexer_get_indexers_request, + build_search_indexer_get_skillset_request, + build_search_indexer_get_skillsets_request, + build_search_indexer_reset_documents_request, + build_search_indexer_reset_indexer_request, + build_search_indexer_reset_skills_request, + build_search_indexer_resync_request, + build_search_indexer_run_indexer_request, ) -from .._configuration import SearchIndexClientConfiguration +from .._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list -class DataSourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`data_sources` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _SearchIndexClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchIndexClientConfiguration] +): @overload - async def create_or_update( + async def create_or_update_synonym_map( self, - data_source_name: str, - data_source: _models2.SearchIndexerDataSource, + synonym_map_name: str, + synonym_map: _models2.SynonymMap, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -143,32 +124,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_synonym_map( self, - data_source_name: str, - data_source: JSON, + synonym_map_name: str, + synonym_map: JSON, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -177,32 +154,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_synonym_map( self, - data_source_name: str, - data_source: IO[bytes], + synonym_map_name: str, + synonym_map: IO[bytes], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -211,44 +184,35 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) - async def create_or_update( + async def create_or_update_synonym_map( self, - data_source_name: str, - data_source: Union[_models2.SearchIndexerDataSource, JSON, IO[bytes]], + synonym_map_name: str, + synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource or updates a datasource if it already exists. + ) -> _models2.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Is one of the - following types: SearchIndexerDataSource, JSON, IO[bytes] Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or - IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Is one of the + following types: SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -270,18 +234,17 @@ async def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndexerDataSource] = kwargs.pop("cls", None) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map else: - _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_data_sources_create_or_update_request( - data_source_name=data_source_name, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + _request = build_search_index_create_or_update_synonym_map_request( + synonym_map_name=synonym_map_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -297,7 +260,7 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -316,7 +279,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexerDataSource, response.json()) + deserialized = _deserialize(_models2.SynonymMap, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -324,18 +287,18 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - async def delete( + async def delete_synonym_map( self, - data_source_name: str, + synonym_map_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes a datasource. + """Deletes a synonym map. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -364,8 +327,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_data_sources_delete_request( - data_source_name=data_source_name, + _request = build_search_index_delete_synonym_map_request( + synonym_map_name=synonym_map_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -378,7 +341,7 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -393,13 +356,13 @@ async def delete( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get(self, data_source_name: str, **kwargs: Any) -> _models2.SearchIndexerDataSource: - """Retrieves a datasource definition. + async def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models2.SynonymMap: + """Retrieves a synonym map definition. - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -413,10 +376,10 @@ async def get(self, data_source_name: str, **kwargs: Any) -> _models2.SearchInde _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.SearchIndexerDataSource] = kwargs.pop("cls", None) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) - _request = build_data_sources_get_request( - data_source_name=data_source_name, + _request = build_search_index_get_synonym_map_request( + synonym_map_name=synonym_map_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -427,7 +390,7 @@ async def get(self, data_source_name: str, **kwargs: Any) -> _models2.SearchInde _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -446,7 +409,7 @@ async def get(self, data_source_name: str, **kwargs: Any) -> _models2.SearchInde if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexerDataSource, response.json()) + deserialized = _deserialize(_models2.SynonymMap, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -454,15 +417,15 @@ async def get(self, data_source_name: str, **kwargs: Any) -> _models2.SearchInde return deserialized # type: ignore @distributed_trace_async - async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListDataSourcesResult: - """Lists all datasources available for a search service. + async def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSynonymMapsResult: + """Lists all synonym maps available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -476,9 +439,9 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.ListDataSourcesResult] = kwargs.pop("cls", None) + cls: ClsType[_models2.ListSynonymMapsResult] = kwargs.pop("cls", None) - _request = build_data_sources_list_request( + _request = build_search_index_get_synonym_maps_request( select=select, api_version=self._config.api_version, headers=_headers, @@ -490,7 +453,7 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -509,7 +472,7 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.ListDataSourcesResult, response.json()) + deserialized = _deserialize(_models2.ListSynonymMapsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -517,65 +480,64 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 return deserialized # type: ignore @overload - async def create( - self, data_source: _models2.SearchIndexerDataSource, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource. + async def create_synonym_map( + self, synonym_map: _models2.SynonymMap, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, data_source: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource. + async def create_synonym_map( + self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Required. - :type data_source: JSON + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, data_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource. + async def create_synonym_map( + self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Required. - :type data_source: IO[bytes] + :param synonym_map: The definition of the synonym map to create. Required. + :type synonym_map: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create( - self, data_source: Union[_models2.SearchIndexerDataSource, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.SearchIndexerDataSource: - """Creates a new datasource. + async def create_synonym_map( + self, synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SynonymMap: + """Creates a new synonym map. - :param data_source: The definition of the datasource to create. Is one of the following types: - SearchIndexerDataSource, JSON, IO[bytes] Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSource or JSON or - IO[bytes] - :return: SearchIndexerDataSource. The SearchIndexerDataSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSource + :param synonym_map: The definition of the synonym map to create. Is one of the following types: + SynonymMap, JSON, IO[bytes] Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :return: SynonymMap. The SynonymMap is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -590,16 +552,16 @@ async def create( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndexerDataSource] = kwargs.pop("cls", None) + cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(data_source, (IOBase, bytes)): - _content = data_source + if isinstance(synonym_map, (IOBase, bytes)): + _content = synonym_map else: - _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_data_sources_create_request( + _request = build_search_index_create_synonym_map_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -612,7 +574,7 @@ async def create( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -631,93 +593,620 @@ async def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexerDataSource, response.json()) + deserialized = _deserialize(_models2.SynonymMap, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + async def create_or_update_index( + self, + index_name: str, + index: _models2.SearchIndex, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. -class IndexersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`indexers` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def reset(self, indexer_name: str, **kwargs: Any) -> None: - """Resets the change tracking state associated with an indexer. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: None - :rtype: None + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_indexers_reset_request( - indexer_name=indexer_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) + @overload + async def create_or_update_index( + self, + index_name: str, + index: JSON, + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: JSON + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_index( + self, + index_name: str, + index: IO[bytes], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_index( + self, + index_name: str, + index: Union[_models2.SearchIndex, JSON, IO[bytes]], + *, + allow_index_downtime: Optional[bool] = None, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + prefer: Literal["return=representation"] = kwargs.pop("prefer") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_or_update_index_request( + index_name=index_name, + allow_index_downtime=allow_index_downtime, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + prefer=prefer, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_index( + self, + index_name: str, + *, + query_source_authorization: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a search index and all the documents it contains. This operation is permanent, with no + recovery option. Make sure you have a master copy of your index definition, data ingestion + code, and a backup of the primary data source in case you need to re-build the index. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_index_delete_index_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_index( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models2.SearchIndex: + """Retrieves an index definition. + + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + _request = build_search_index_get_index_request( + index_name=index_name, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_indexes(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SearchIndex"]: + """Lists all indexes available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: An iterator like instance of SearchIndex + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchIndex]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_list_indexes_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchIndex], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_index( + self, index: _models2.SearchIndex, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_index( + self, index: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_index( + self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Required. + :type index: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_index( + self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndex: + """Creates a new search index. + + :param index: The definition of the index to create. Is one of the following types: + SearchIndex, JSON, IO[bytes] Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] + :return: SearchIndex. The SearchIndex is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_index_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndex, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def resync(self, indexer_name: str, **kwargs: Any) -> None: - """Resync selective options from the datasource to be re-ingested by the indexer.". + async def get_index_statistics( + self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any + ) -> _models2.GetIndexStatisticsResult: + """Returns statistics for the given index, including a document count and storage usage. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: None - :rtype: None + :param index_name: The name of the index. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -731,10 +1220,11 @@ async def resync(self, indexer_name: str, **kwargs: Any) -> None: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models2.GetIndexStatisticsResult] = kwargs.pop("cls", None) - _request = build_indexers_resync_request( - indexer_name=indexer_name, + _request = build_search_index_get_index_statistics_request( + index_name=index_name, + query_source_authorization=query_source_authorization, api_version=self._config.api_version, headers=_headers, params=_params, @@ -744,139 +1234,139 @@ async def resync(self, indexer_name: str, **kwargs: Any) -> None: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.GetIndexStatisticsResult, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - async def reset_docs( + async def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[_models2.DocumentKeysOrIds] = None, + index_name: str, + request: _models2.AnalyzeTextOptions, *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeTextOptions + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def reset_docs( + async def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[JSON] = None, + index_name: str, + request: JSON, *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Default value is None. - :type keys_or_ids: JSON - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: JSON + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def reset_docs( + async def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[IO[bytes]] = None, + index_name: str, + request: IO[bytes], *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Default value is None. - :type keys_or_ids: IO[bytes] - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Required. + :type request: IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def reset_docs( + async def analyze_text( self, - indexer_name: str, - keys_or_ids: Optional[Union[_models2.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + index_name: str, + request: Union[_models2.AnalyzeTextOptions, JSON, IO[bytes]], *, - overwrite: Optional[bool] = None, + query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> None: - """Resets specific documents in the datasource to be selectively re-ingested by the indexer. + ) -> _models2.AnalyzeResult: + """Shows how an analyzer breaks text into tokens. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, - the document key field must be specified in the indexer configuration. If ids are provided, the - document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, - IO[bytes] Default value is None. - :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or - IO[bytes] - :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the - keys or ids in this payload will be queued to be re-ingested. Default value is None. - :paramtype overwrite: bool - :return: None - :rtype: None + :param index_name: The name of the index. Required. + :type index_name: str + :param request: The text and analyzer or analysis components to test. Is one of the following + types: AnalyzeTextOptions, JSON, IO[bytes] Required. + :type request: ~azure.search.documents.indexes.models.AnalyzeTextOptions or JSON or IO[bytes] + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.AnalyzeResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -891,22 +1381,18 @@ async def reset_docs( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - content_type = content_type if keys_or_ids else None - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models2.AnalyzeResult] = kwargs.pop("cls", None) - content_type = content_type or "application/json" if keys_or_ids else None + content_type = content_type or "application/json" _content = None - if isinstance(keys_or_ids, (IOBase, bytes)): - _content = keys_or_ids + if isinstance(request, (IOBase, bytes)): + _content = request else: - if keys_or_ids is not None: - _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - else: - _content = None + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexers_reset_docs_request( - indexer_name=indexer_name, - overwrite=overwrite, + _request = build_search_index_analyze_text_request( + index_name=index_name, + query_source_authorization=query_source_authorization, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -918,95 +1404,50 @@ async def reset_docs( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def run(self, indexer_name: str, **kwargs: Any) -> None: - """Runs an indexer on-demand. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_indexers_run_request( - indexer_name=indexer_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.AnalyzeResult, response.json()) if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - async def create_or_update( + async def create_or_update_alias( self, - indexer_name: str, - indexer: _models2.SearchIndexer, + alias_name: str, + alias: _models2.SearchAlias, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1015,36 +1456,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_alias( self, - indexer_name: str, - indexer: JSON, + alias_name: str, + alias: JSON, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1053,36 +1486,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_alias( self, - indexer_name: str, - indexer: IO[bytes], + alias_name: str, + alias: IO[bytes], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -1091,52 +1516,35 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) - async def create_or_update( + async def create_or_update_alias( self, - indexer_name: str, - indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], + alias_name: str, + alias: Union[_models2.SearchAlias, JSON, IO[bytes]], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. + ) -> _models2.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Is one of the following - types: SearchIndexer, JSON, IO[bytes] Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1158,19 +1566,17 @@ async def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer + if isinstance(alias, (IOBase, bytes)): + _content = alias else: - _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexers_create_or_update_request( - indexer_name=indexer_name, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + _request = build_search_index_create_or_update_alias_request( + alias_name=alias_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -1186,7 +1592,7 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1205,7 +1611,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexer, response.json()) + deserialized = _deserialize(_models2.SearchAlias, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1213,18 +1619,19 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - async def delete( + async def delete_alias( self, - indexer_name: str, + alias_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes an indexer. + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str + :param alias_name: The name of the alias. Required. + :type alias_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -1253,8 +1660,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_indexers_delete_request( - indexer_name=indexer_name, + _request = build_search_index_delete_alias_request( + alias_name=alias_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -1267,7 +1674,7 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1282,13 +1689,13 @@ async def delete( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexer: - """Retrieves an indexer definition. + async def get_alias(self, alias_name: str, **kwargs: Any) -> _models2.SearchAlias: + """Retrieves an alias definition. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :param alias_name: The name of the alias. Required. + :type alias_name: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1302,10 +1709,10 @@ async def get(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexer: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) - _request = build_indexers_get_request( - indexer_name=indexer_name, + _request = build_search_index_get_alias_request( + alias_name=alias_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1316,7 +1723,7 @@ async def get(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexer: _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1335,25 +1742,27 @@ async def get(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexer: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexer, response.json()) + deserialized = _deserialize(_models2.SearchAlias, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace_async - async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListIndexersResult: - """Lists all indexers available for a search service. + @distributed_trace + def list_aliases(self, **kwargs: Any) -> AsyncItemPaged["_models2.SearchAlias"]: + """Lists all aliases available for a search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult + :return: An iterator like instance of SearchAlias + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchAlias]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1362,178 +1771,127 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models2.ListIndexersResult] = kwargs.pop("cls", None) + _request = build_search_index_list_aliases_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_indexers_list_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchAlias], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListIndexersResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload - async def create( - self, indexer: _models2.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer. + async def create_alias( + self, alias: _models2.SearchAlias, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. - :param indexer: The definition of the indexer to create. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :param alias: The definition of the alias to create. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer. + async def create_alias( + self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. - :param indexer: The definition of the indexer to create. Required. - :type indexer: JSON + :param alias: The definition of the alias to create. Required. + :type alias: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer. - - :param indexer: The definition of the indexer to create. Required. - :type indexer: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer. - - :param indexer: The definition of the indexer to create. Is one of the following types: - SearchIndexer, JSON, IO[bytes] Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(indexer, (IOBase, bytes)): - _content = indexer - else: - _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_indexers_create_request( - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SearchIndexer, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + async def create_alias( + self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. - return deserialized # type: ignore + :param alias: The definition of the alias to create. Required. + :type alias: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def get_status(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexerStatus: - """Returns the current status and execution history of an indexer. + async def create_alias( + self, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchAlias: + """Creates a new search alias. - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus + :param alias: The definition of the alias to create. Is one of the following types: + SearchAlias, JSON, IO[bytes] Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] + :return: SearchAlias. The SearchAlias is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1544,14 +1902,23 @@ async def get_status(self, indexer_name: str, **kwargs: Any) -> _models2.SearchI } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.SearchIndexerStatus] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) - _request = build_indexers_get_status_request( - indexer_name=indexer_name, + content_type = content_type or "application/json" + _content = None + if isinstance(alias, (IOBase, bytes)): + _content = alias + else: + _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_alias_request( + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -1561,13 +1928,13 @@ async def get_status(self, indexer_name: str, **kwargs: Any) -> _models2.SearchI _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -1580,57 +1947,30 @@ async def get_status(self, indexer_name: str, **kwargs: Any) -> _models2.SearchI if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexerStatus, response.json()) + deserialized = _deserialize(_models2.SearchAlias, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class SkillsetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`skillsets` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - async def create_or_update( + async def create_or_update_agent( self, - skillset_name: str, - skillset: _models2.SearchIndexerSkillset, + agent_name: str, + knowledge_agent: _models2.KnowledgeAgent, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1639,37 +1979,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_agent( self, - skillset_name: str, - skillset: JSON, + agent_name: str, + knowledge_agent: JSON, *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1678,37 +2009,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_agent( self, - skillset_name: str, - skillset: IO[bytes], + agent_name: str, + knowledge_agent: IO[bytes], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Required. + :type knowledge_agent: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -1717,53 +2039,36 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) - async def create_or_update( + async def create_or_update_agent( self, - skillset_name: str, - skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], + agent_name: str, + knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], *, - skip_indexer_reset_requirement_for_cache: Optional[bool] = None, - disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. + ) -> _models2.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param knowledge_agent: The definition of the agent to create or update. Is one of the + following types: KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1785,19 +2090,17 @@ async def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent else: - _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_skillsets_create_or_update_request( - skillset_name=skillset_name, - skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + _request = build_search_index_create_or_update_agent_request( + agent_name=agent_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -1813,13 +2116,13 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -1832,7 +2135,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1840,18 +2143,19 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - async def delete( + async def delete_agent( self, - skillset_name: str, + agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes a skillset in a search service. + """Deletes a search alias and its associated mapping to an index. This operation is permanent, + with no recovery option. The mapped index is untouched by this operation. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str + :param agent_name: The name of the agent. Required. + :type agent_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -1880,8 +2184,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_skillsets_delete_request( - skillset_name=skillset_name, + _request = build_search_index_delete_agent_request( + agent_name=agent_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -1894,91 +2198,28 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get(self, skillset_name: str, **kwargs: Any) -> _models2.SearchIndexerSkillset: - """Retrieves a skillset in a search service. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) - - _request = build_skillsets_get_request( - skillset_name=skillset_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSkillsetsResult: - """List all skillsets in a search service. + async def get_agent(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: + """Retrieves an agent definition. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult + :param agent_name: The name of the agent. Required. + :type agent_name: str + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1992,10 +2233,10 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.ListSkillsetsResult] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) - _request = build_skillsets_list_request( - select=select, + _request = build_search_index_get_agent_request( + agent_name=agent_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2006,7 +2247,7 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2025,76 +2266,20 @@ async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2 if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.ListSkillsetsResult, response.json()) + deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def create( - self, skillset: _models2.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service. - - :param skillset: The skillset containing one or more skills to create in a search service. - Required. - :type skillset: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace_async - async def create( - self, skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service. + async def list_agents(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: + """Lists all agents available for a search service. - :param skillset: The skillset containing one or more skills to create in a search service. Is - one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or - IO[bytes] - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2105,23 +2290,13 @@ async def create( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(skillset, (IOBase, bytes)): - _content = skillset - else: - _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models2.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) - _request = build_skillsets_create_request( - content_type=content_type, + _request = build_search_index_list_agents_request( api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -2131,13 +2306,13 @@ async def create( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -2150,7 +2325,7 @@ async def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) + deserialized = _deserialize(_models2.ListKnowledgeAgentsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2158,85 +2333,65 @@ async def create( return deserialized # type: ignore @overload - async def reset_skills( - self, - skillset_name: str, - skill_names: _models2.SkillNames, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + async def create_agent( + self, knowledge_agent: _models2.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def reset_skills( - self, skillset_name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + async def create_agent( + self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Required. - :type skill_names: JSON + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def reset_skills( - self, skillset_name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + async def create_agent( + self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Required. - :type skill_names: IO[bytes] + :param knowledge_agent: The definition of the agent to create. Required. + :type knowledge_agent: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: None - :rtype: None + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def reset_skills( - self, skillset_name: str, skill_names: Union[_models2.SkillNames, JSON, IO[bytes]], **kwargs: Any - ) -> None: - """Reset an existing skillset in a search service. + async def create_agent( + self, knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeAgent: + """Creates a new agent. - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skill_names: The names of the skills to reset. If not specified, all skills in the - skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. - :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] - :return: None - :rtype: None + :param knowledge_agent: The definition of the agent to create. Is one of the following types: + KnowledgeAgent, JSON, IO[bytes] Required. + :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or + IO[bytes] + :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2251,17 +2406,16 @@ async def reset_skills( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(skill_names, (IOBase, bytes)): - _content = skill_names + if isinstance(knowledge_agent, (IOBase, bytes)): + _content = knowledge_agent else: - _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_skillsets_reset_skills_request( - skillset_name=skillset_name, + _request = build_search_index_create_agent_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -2273,56 +2427,50 @@ async def reset_skills( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class SynonymMapsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`synonym_maps` attribute. - """ + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + return deserialized # type: ignore @overload - async def create_or_update( + async def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: _models2.SynonymMap, + source_name: str, + knowledge_source: _models2.KnowledgeSource, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2331,28 +2479,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: JSON, + source_name: str, + knowledge_source: JSON, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: JSON + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2361,28 +2509,28 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: IO[bytes], + source_name: str, + knowledge_source: IO[bytes], *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -2391,35 +2539,36 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_or_update( + async def create_or_update_knowledge_source( self, - synonym_map_name: str, - synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], + source_name: str, + knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source or updates an knowledge source if it already exists. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Is one of the - following types: SynonymMap, JSON, IO[bytes] Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Is one of + the following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2441,17 +2590,17 @@ async def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source else: - _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_synonym_maps_create_or_update_request( - synonym_map_name=synonym_map_name, + _request = build_search_index_create_or_update_knowledge_source_request( + source_name=source_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -2467,7 +2616,7 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2486,7 +2635,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SynonymMap, response.json()) + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2494,18 +2643,18 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - async def delete( + async def delete_knowledge_source( self, - synonym_map_name: str, + source_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes a synonym map. + """Deletes an existing knowledge source. - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str + :param source_name: The name of the knowledge source. Required. + :type source_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -2534,8 +2683,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_synonym_maps_delete_request( - synonym_map_name=synonym_map_name, + _request = build_search_index_delete_knowledge_source_request( + source_name=source_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -2548,7 +2697,7 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2563,188 +2712,13 @@ async def delete( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get(self, synonym_map_name: str, **kwargs: Any) -> _models2.SynonymMap: - """Retrieves a synonym map definition. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) - - _request = build_synonym_maps_get_request( - synonym_map_name=synonym_map_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SynonymMap, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSynonymMapsResult: - """Lists all synonym maps available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models2.ListSynonymMapsResult] = kwargs.pop("cls", None) - - _request = build_synonym_maps_list_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListSynonymMapsResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, synonym_map: _models2.SynonymMap, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map. - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, synonym_map: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map. - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, synonym_map: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map. - - :param synonym_map: The definition of the synonym map to create. Required. - :type synonym_map: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map. + async def get_knowledge_source(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource: + """Retrieves a knowledge source definition. - :param synonym_map: The definition of the synonym map to create. Is one of the following types: - SynonymMap, JSON, IO[bytes] Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap or JSON or IO[bytes] - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2755,23 +2729,14 @@ async def create( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(synonym_map, (IOBase, bytes)): - _content = synonym_map - else: - _content = json.dumps(synonym_map, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) - _request = build_synonym_maps_create_request( - content_type=content_type, + _request = build_search_index_get_knowledge_source_request( + source_name=source_name, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -2781,13 +2746,13 @@ async def create( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -2800,193 +2765,20 @@ async def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SynonymMap, response.json()) + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`indexes` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - index_name: str, - index: _models2.SearchIndex, - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - index_name: str, - index: JSON, - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: JSON - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - index_name: str, - index: IO[bytes], - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace_async - async def create_or_update( - self, - index_name: str, - index: Union[_models2.SearchIndex, JSON, IO[bytes]], - *, - allow_index_downtime: Optional[bool] = None, - query_source_authorization: Optional[str] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. + async def list_knowledge_sources(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: + """Lists all knowledge sources available for a search service. - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Is one of the following types: - SearchIndex, JSON, IO[bytes] Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with + MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2995,38 +2787,15 @@ async def create_or_update( 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models2.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - _request = build_indexes_create_or_update_request( - index_name=index_name, - allow_index_downtime=allow_index_downtime, - query_source_authorization=query_source_authorization, - etag=etag, - match_condition=match_condition, - prefer=prefer, - content_type=content_type, + _request = build_search_index_list_knowledge_sources_request( api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -3036,13 +2805,13 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -3055,40 +2824,73 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndex, response.json()) + deserialized = _deserialize(_models2.ListKnowledgeSourcesResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + async def create_knowledge_source( + self, knowledge_source: _models2.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_knowledge_source( + self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_knowledge_source( + self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. + + :param knowledge_source: The definition of the knowledge source to create. Required. + :type knowledge_source: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace_async - async def delete( - self, - index_name: str, - *, - query_source_authorization: Optional[str] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> None: - """Deletes a search index and all the documents it contains. This operation is permanent, with no - recovery option. Make sure you have a master copy of your index definition, data ingestion - code, and a backup of the primary data source in case you need to re-build the index. + async def create_knowledge_source( + self, knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeSource: + """Creates a new knowledge source. - :param index_name: The name of the index. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None + :param knowledge_source: The definition of the knowledge source to create. Is one of the + following types: KnowledgeSource, JSON, IO[bytes] Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + IO[bytes] + :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3097,25 +2899,25 @@ async def delete( 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) - _request = build_indexes_delete_request( - index_name=index_name, - query_source_authorization=query_source_authorization, - etag=etag, - match_condition=match_condition, + content_type = content_type or "application/json" + _content = None + if isinstance(knowledge_source, (IOBase, bytes)): + _content = knowledge_source + else: + _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_index_create_knowledge_source_request( + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -3124,35 +2926,39 @@ async def delete( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204, 404]: + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def get( - self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models2.SearchIndex: - """Retrieves an index definition. + async def list_index_stats_summary(self, **kwargs: Any) -> _models2.SearchServiceStatistics: + """Gets service level statistics for a search service. - :param index_name: The name of the index. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3166,11 +2972,9 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchServiceStatistics] = kwargs.pop("cls", None) - _request = build_indexes_get_request( - index_name=index_name, - query_source_authorization=query_source_authorization, + _request = build_search_index_list_index_stats_summary_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -3181,7 +2985,7 @@ async def get( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3200,7 +3004,7 @@ async def get( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndex, response.json()) + deserialized = _deserialize(_models2.SearchServiceStatistics, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3208,22 +3012,23 @@ async def get( return deserialized # type: ignore @distributed_trace - def list(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SearchIndex"]: - """Lists all indexes available for a search service. + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + def get_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: + """Retrieves a summary of statistics for all indexes in the search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: An iterator like instance of SearchIndex + :return: An iterator like instance of IndexStatisticsSummary :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndex] + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models2.SearchIndex]] = kwargs.pop("cls", None) + cls: ClsType[list[_models2.IndexStatisticsSummary]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3236,8 +3041,7 @@ def list(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged def prepare_request(next_link=None): if not next_link: - _request = build_indexes_list_request( - select=select, + _request = build_search_index_get_index_stats_summary_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -3273,7 +3077,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models2.SearchIndex], deserialized.get("value", [])) + list_of_elem = _deserialize(list[_models2.IndexStatisticsSummary], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return None, AsyncList(list_of_elem) @@ -3282,7 +3086,7 @@ async def get_next(next_link=None): _request = prepare_request(next_link) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -3296,63 +3100,150 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) + +class _SearchIndexerClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchIndexerClientConfiguration] +): + @overload - async def create( - self, index: _models2.SearchIndex, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index. + async def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: _models2.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, index: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index. + async def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: JSON, + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Required. - :type index: JSON + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, index: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index. + async def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: IO[bytes], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + content_type: str = "application/json", + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Required. - :type index: IO[bytes] + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Required. + :type data_source: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create(self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kwargs: Any) -> _models2.SearchIndex: - """Creates a new search index. + @api_version_validation( + params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], + ) + async def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: Union[_models2.SearchIndexerDataSourceConnection, JSON, IO[bytes]], + *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource or updates a datasource if it already exists. - :param index: The definition of the index to create. Is one of the following types: - SearchIndex, JSON, IO[bytes] Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex or JSON or IO[bytes] - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :param data_source: The definition of the datasource to create or update. Is one of the + following types: SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or + JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3361,22 +3252,34 @@ async def create(self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kw 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} + prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(index, (IOBase, bytes)): - _content = index + if isinstance(data_source, (IOBase, bytes)): + _content = data_source else: - _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_indexes_create_request( + _request = build_search_indexer_create_or_update_data_source_connection_request( + data_source_name=data_source_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + etag=etag, + match_condition=match_condition, + prefer=prefer, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -3389,13 +3292,13 @@ async def create(self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kw _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -3408,7 +3311,7 @@ async def create(self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kw if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchIndex, response.json()) + deserialized = _deserialize(_models2.SearchIndexerDataSourceConnection, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3416,20 +3319,25 @@ async def create(self, index: Union[_models2.SearchIndex, JSON, IO[bytes]], **kw return deserialized # type: ignore @distributed_trace_async - async def get_statistics( - self, index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models2.GetIndexStatisticsResult: - """Returns statistics for the given index, including a document count and storage usage. + async def delete_data_source_connection( + self, + data_source_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> None: + """Deletes a datasource. - :param index_name: The name of the index. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. - :paramtype query_source_authorization: str - :return: GetIndexStatisticsResult. The GetIndexStatisticsResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.GetIndexStatisticsResult + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3438,16 +3346,75 @@ async def get_statistics( 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.GetIndexStatisticsResult] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_indexes_get_statistics_request( - index_name=index_name, - query_source_authorization=query_source_authorization, + _request = build_search_indexer_delete_data_source_connection_request( + data_source_name=data_source_name, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_data_source_connection( + self, data_source_name: str, **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Retrieves a datasource definition. + + :param data_source_name: The name of the datasource. Required. + :type data_source_name: str + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) + + _request = build_search_indexer_get_data_source_connection_request( + data_source_name=data_source_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3458,7 +3425,7 @@ async def get_statistics( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3477,119 +3444,25 @@ async def get_statistics( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.GetIndexStatisticsResult, response.json()) + deserialized = _deserialize(_models2.SearchIndexerDataSourceConnection, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def analyze( - self, - index_name: str, - request: _models2.AnalyzeRequest, - *, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models2.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def analyze( - self, - index_name: str, - request: JSON, - *, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models2.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def analyze( - self, - index_name: str, - request: IO[bytes], - *, - query_source_authorization: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models2.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. - - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Required. - :type request: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace_async - async def analyze( - self, - index_name: str, - request: Union[_models2.AnalyzeRequest, JSON, IO[bytes]], - *, - query_source_authorization: Optional[str] = None, - **kwargs: Any - ) -> _models2.AnalyzeResult: - """Shows how an analyzer breaks text into tokens. + async def get_data_source_connections( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> _models2.ListDataSourcesResult: + """Lists all datasources available for a search service. - :param index_name: The name of the index. Required. - :type index_name: str - :param request: The text and analyzer or analysis components to test. Is one of the following - types: AnalyzeRequest, JSON, IO[bytes] Required. - :type request: ~azure.search.documents.indexes.models.AnalyzeRequest or JSON or IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :return: AnalyzeResult. The AnalyzeResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.AnalyzeResult + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3600,25 +3473,14 @@ async def analyze( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.AnalyzeResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(request, (IOBase, bytes)): - _content = request - else: - _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models2.ListDataSourcesResult] = kwargs.pop("cls", None) - _request = build_indexes_analyze_request( - index_name=index_name, - query_source_authorization=query_source_authorization, - content_type=content_type, + _request = build_search_indexer_get_data_source_connections_request( + select=select, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -3628,7 +3490,7 @@ async def analyze( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3647,161 +3509,81 @@ async def analyze( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.AnalyzeResult, response.json()) + deserialized = _deserialize(_models2.ListDataSourcesResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class AliasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`aliases` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - async def create_or_update( + async def create_data_source_connection( self, - alias_name: str, - alias: _models2.SearchAlias, + data_source: _models2.SearchIndexerDataSourceConnection, *, content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias + :param data_source: The definition of the datasource to create. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - alias_name: str, - alias: JSON, - *, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: JSON + @overload + async def create_data_source_connection( + self, data_source: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. + + :param data_source: The definition of the datasource to create. Required. + :type data_source: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( - self, - alias_name: str, - alias: IO[bytes], - *, - content_type: str = "application/json", - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + async def create_data_source_connection( + self, data_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] + :param data_source: The definition of the datasource to create. Required. + :type data_source: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": [ - "api_version", - "prefer", - "client_request_id", - "alias_name", - "content_type", - "accept", - "etag", - "match_condition", - ] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def create_or_update( - self, - alias_name: str, - alias: Union[_models2.SearchAlias, JSON, IO[bytes]], - *, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. + async def create_data_source_connection( + self, data_source: Union[_models2.SearchIndexerDataSourceConnection, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexerDataSourceConnection: + """Creates a new datasource. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Is one of the following types: - SearchAlias, JSON, IO[bytes] Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :param data_source: The definition of the datasource to create. Is one of the following types: + SearchIndexerDataSourceConnection, JSON, IO[bytes] Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection or + JSON or IO[bytes] + :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible + with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3810,33 +3592,22 @@ async def create_or_update( 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias + if isinstance(data_source, (IOBase, bytes)): + _content = data_source else: - _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(data_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_aliases_create_or_update_request( - alias_name=alias_name, - etag=etag, - match_condition=match_condition, - prefer=prefer, + _request = build_search_indexer_create_data_source_connection_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -3849,13 +3620,13 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -3868,7 +3639,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SearchAlias, response.json()) + deserialized = _deserialize(_models2.SearchIndexerDataSourceConnection, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3876,31 +3647,11 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "etag", "match_condition"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def delete( - self, - alias_name: str, - *, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. + async def reset_indexer(self, indexer_name: str, **kwargs: Any) -> None: + """Resets the change tracking state associated with an indexer. - :param alias_name: The name of the alias. Required. - :type alias_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3911,12 +3662,6 @@ async def delete( 409: ResourceExistsError, 304: ResourceNotModifiedError, } - if match_condition == MatchConditions.IfNotModified: - error_map[412] = ResourceModifiedError - elif match_condition == MatchConditions.IfPresent: - error_map[412] = ResourceNotFoundError - elif match_condition == MatchConditions.IfMissing: - error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} @@ -3924,10 +3669,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_aliases_delete_request( - alias_name=alias_name, - etag=etag, - match_condition=match_condition, + _request = build_search_indexer_reset_indexer_request( + indexer_name=indexer_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3938,13 +3681,13 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204, 404]: + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) @@ -3955,16 +3698,16 @@ async def delete( @distributed_trace_async @api_version_validation( method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "alias_name", "accept"]}, + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], ) - async def get(self, alias_name: str, **kwargs: Any) -> _models2.SearchAlias: - """Retrieves an alias definition. + async def resync(self, indexer_name: str, **kwargs: Any) -> None: + """Resync selective options from the datasource to be re-ingested by the indexer.". - :param alias_name: The name of the alias. Required. - :type alias_name: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3978,10 +3721,10 @@ async def get(self, alias_name: str, **kwargs: Any) -> _models2.SearchAlias: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_aliases_get_request( - alias_name=alias_name, + _request = build_search_indexer_resync_request( + indexer_name=indexer_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3991,184 +3734,139 @@ async def get(self, alias_name: str, **kwargs: Any) -> _models2.SearchAlias: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SearchAlias, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def list(self, **kwargs: Any) -> AsyncItemPaged["_models2.SearchAlias"]: - """Lists all aliases available for a search service. - - :return: An iterator like instance of SearchAlias - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchAlias] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models2.SearchAlias]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_aliases_list_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models2.SearchAlias], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response + raise HttpResponseError(response=response, model=error) - return AsyncItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, None, {}) # type: ignore @overload - async def create( - self, alias: _models2.SearchAlias, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias. + async def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[_models2.DocumentKeysOrIds] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, alias: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias. + async def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[JSON] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Required. - :type alias: JSON + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: JSON + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, alias: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias. + async def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[IO[bytes]] = None, + *, + overwrite: Optional[bool] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Required. - :type alias: IO[bytes] + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Default value is None. + :type keys_or_ids: IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async @api_version_validation( method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, + params_added_on={ + "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] + }, api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], ) - async def create(self, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], **kwargs: Any) -> _models2.SearchAlias: - """Creates a new search alias. + async def reset_documents( + self, + indexer_name: str, + keys_or_ids: Optional[Union[_models2.DocumentKeysOrIds, JSON, IO[bytes]]] = None, + *, + overwrite: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Resets specific documents in the datasource to be selectively re-ingested by the indexer. - :param alias: The definition of the alias to create. Is one of the following types: - SearchAlias, JSON, IO[bytes] Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias or JSON or IO[bytes] - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param keys_or_ids: The keys or ids of the documents to be re-ingested. If keys are provided, + the document key field must be specified in the indexer configuration. If ids are provided, the + document key field is ignored. Is one of the following types: DocumentKeysOrIds, JSON, + IO[bytes] Default value is None. + :type keys_or_ids: ~azure.search.documents.indexes.models.DocumentKeysOrIds or JSON or + IO[bytes] + :keyword overwrite: If false, keys or ids will be appended to existing ones. If true, only the + keys or ids in this payload will be queued to be re-ingested. Default value is None. + :paramtype overwrite: bool + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4183,16 +3881,22 @@ async def create(self, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], **kw _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) + content_type = content_type if keys_or_ids else None + cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/json" + content_type = content_type or "application/json" if keys_or_ids else None _content = None - if isinstance(alias, (IOBase, bytes)): - _content = alias + if isinstance(keys_or_ids, (IOBase, bytes)): + _content = keys_or_ids else: - _content = json.dumps(alias, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if keys_or_ids is not None: + _content = json.dumps(keys_or_ids, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + else: + _content = None - _request = build_aliases_create_request( + _request = build_search_indexer_reset_documents_request( + indexer_name=indexer_name, + overwrite=overwrite, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -4204,68 +3908,95 @@ async def create(self, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], **kw } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SearchAlias, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore - return deserialized # type: ignore + @distributed_trace_async + async def run_indexer(self, indexer_name: str, **kwargs: Any) -> None: + """Runs an indexer on-demand. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_search_indexer_run_indexer_request( + indexer_name=indexer_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) -class AgentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + response = pipeline_response.http_response - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`agents` attribute. - """ + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + if cls: + return cls(pipeline_response, None, {}) # type: ignore @overload async def create_or_update( self, - agent_name: str, - knowledge_agent: _models2.KnowledgeAgent, + indexer_name: str, + indexer: _models2.SearchIndexer, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4274,28 +4005,36 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create_or_update( self, - agent_name: str, - knowledge_agent: JSON, + indexer_name: str, + indexer: JSON, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: JSON + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4304,28 +4043,36 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create_or_update( self, - agent_name: str, - knowledge_agent: IO[bytes], + indexer_name: str, + indexer: IO[bytes], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: IO[bytes] + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -4334,52 +4081,52 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async @api_version_validation( - method_added_on="2025-08-01-preview", params_added_on={ "2025-08-01-preview": [ - "api_version", - "prefer", - "client_request_id", - "agent_name", - "content_type", - "accept", - "etag", - "match_condition", + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", ] }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) async def create_or_update( self, - agent_name: str, - knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], + indexer_name: str, + indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + ) -> _models2.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Is one of the - following types: KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Is one of the following + types: SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4401,17 +4148,19 @@ async def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent + if isinstance(indexer, (IOBase, bytes)): + _content = indexer else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_create_or_update_request( - agent_name=agent_name, + _request = build_search_indexer_create_or_update_request( + indexer_name=indexer_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, etag=etag, match_condition=match_condition, prefer=prefer, @@ -4427,13 +4176,13 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -4446,7 +4195,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models2.SearchIndexer, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -4454,26 +4203,18 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "etag", "match_condition"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def delete( + async def delete_indexer( self, - agent_name: str, + indexer_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. + """Deletes an indexer. - :param agent_name: The name of the agent. Required. - :type agent_name: str + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -4502,8 +4243,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_agents_delete_request( - agent_name=agent_name, + _request = build_search_indexer_delete_indexer_request( + indexer_name=indexer_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -4516,7 +4257,7 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -4531,18 +4272,13 @@ async def delete( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "agent_name", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def get(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: - """Retrieves an agent definition. + async def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexer: + """Retrieves an indexer definition. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4556,10 +4292,10 @@ async def get(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) - _request = build_agents_get_request( - agent_name=agent_name, + _request = build_search_indexer_get_indexer_request( + indexer_name=indexer_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4570,7 +4306,7 @@ async def get(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -4589,7 +4325,7 @@ async def get(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models2.SearchIndexer, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -4597,17 +4333,15 @@ async def get(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def list(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: - """Lists all agents available for a search service. + async def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListIndexersResult: + """Lists all indexers available for a search service. - :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListIndexersResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4621,9 +4355,10 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) + cls: ClsType[_models2.ListIndexersResult] = kwargs.pop("cls", None) - _request = build_agents_list_request( + _request = build_search_indexer_get_indexers_request( + select=select, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4634,7 +4369,7 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -4653,7 +4388,7 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.ListKnowledgeAgentsResult, response.json()) + deserialized = _deserialize(_models2.ListIndexersResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -4661,70 +4396,134 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: return deserialized # type: ignore @overload - async def create( - self, knowledge_agent: _models2.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_indexer( + self, indexer: _models2.SearchIndexer, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer: The definition of the indexer to create. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_indexer( + self, indexer: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: JSON + :param indexer: The definition of the indexer to create. Required. + :type indexer: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_indexer( + self, indexer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: IO[bytes] + :param indexer: The definition of the indexer to create. Required. + :type indexer: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def create( - self, knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_indexer( + self, indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexer: + """Creates a new indexer. + + :param indexer: The definition of the indexer to create. Is one of the following types: + SearchIndexer, JSON, IO[bytes] Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer or JSON or IO[bytes] + :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(indexer, (IOBase, bytes)): + _content = indexer + else: + _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_search_indexer_create_indexer_request( + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models2.SearchIndexer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_indexer_status(self, indexer_name: str, **kwargs: Any) -> _models2.SearchIndexerStatus: + """Returns the current status and execution history of an indexer. - :param knowledge_agent: The definition of the agent to create. Is one of the following types: - KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :return: SearchIndexerStatus. The SearchIndexerStatus is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerStatus :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4735,23 +4534,14 @@ async def create( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent - else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models2.SearchIndexerStatus] = kwargs.pop("cls", None) - _request = build_agents_create_request( - content_type=content_type, + _request = build_search_indexer_get_indexer_status_request( + indexer_name=indexer_name, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -4761,13 +4551,13 @@ async def create( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -4780,48 +4570,39 @@ async def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models2.SearchIndexerStatus, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class SourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.SearchIndexClient`'s - :attr:`sources` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: SearchIndexClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @overload - async def create_or_update( + async def create_or_update_skillset( self, - source_name: str, - knowledge_source: _models2.KnowledgeSource, + skillset_name: str, + skillset: _models2.SearchIndexerSkillset, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4830,28 +4611,37 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_skillset( self, - source_name: str, - knowledge_source: JSON, + skillset_name: str, + skillset: JSON, *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: JSON + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: JSON + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4860,28 +4650,37 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update( + async def create_or_update_skillset( self, - source_name: str, - knowledge_source: IO[bytes], + skillset_name: str, + skillset: IO[bytes], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -4890,52 +4689,53 @@ async def create_or_update( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async @api_version_validation( - method_added_on="2025-08-01-preview", params_added_on={ "2025-08-01-preview": [ - "api_version", - "prefer", - "client_request_id", - "source_name", - "content_type", - "accept", - "etag", - "match_condition", + "skip_indexer_reset_requirement_for_cache", + "disable_cache_reprocessing_change_detection", ] }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - async def create_or_update( + async def create_or_update_skillset( self, - source_name: str, - knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], + skillset_name: str, + skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], *, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Is one of - the following types: KnowledgeSource, JSON, IO[bytes] Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Is one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or IO[bytes] + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4957,17 +4757,19 @@ async def create_or_update( prefer: Literal["return=representation"] = kwargs.pop("prefer") content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source + if isinstance(skillset, (IOBase, bytes)): + _content = skillset else: - _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_sources_create_or_update_request( - source_name=source_name, + _request = build_search_indexer_create_or_update_skillset_request( + skillset_name=skillset_name, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, etag=etag, match_condition=match_condition, prefer=prefer, @@ -4983,7 +4785,7 @@ async def create_or_update( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5002,7 +4804,7 @@ async def create_or_update( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5010,25 +4812,18 @@ async def create_or_update( return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "client_request_id", "source_name", "etag", "match_condition"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def delete( + async def delete_skillset( self, - source_name: str, + skillset_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes an existing knowledge source. + """Deletes a skillset in a search service. - :param source_name: The name of the knowledge source. Required. - :type source_name: str + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -5057,8 +4852,8 @@ async def delete( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_sources_delete_request( - source_name=source_name, + _request = build_search_indexer_delete_skillset_request( + skillset_name=skillset_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -5071,7 +4866,7 @@ async def delete( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5086,18 +4881,13 @@ async def delete( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "source_name", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def get(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource: - """Retrieves a knowledge source definition. + async def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models2.SearchIndexerSkillset: + """Retrieves a skillset in a search service. - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5111,10 +4901,10 @@ async def get(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) - _request = build_sources_get_request( - source_name=source_name, + _request = build_search_indexer_get_skillset_request( + skillset_name=skillset_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5125,7 +4915,7 @@ async def get(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5144,7 +4934,7 @@ async def get(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5152,17 +4942,15 @@ async def get(self, source_name: str, **kwargs: Any) -> _models2.KnowledgeSource return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def list(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: - """Lists all knowledge sources available for a search service. + async def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSkillsetsResult: + """List all skillsets in a search service. - :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5176,9 +4964,10 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) + cls: ClsType[_models2.ListSkillsetsResult] = kwargs.pop("cls", None) - _request = build_sources_list_request( + _request = build_search_indexer_get_skillsets_request( + select=select, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5189,7 +4978,7 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5208,7 +4997,7 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.ListKnowledgeSourcesResult, response.json()) + deserialized = _deserialize(_models2.ListSkillsetsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5216,70 +5005,68 @@ async def list(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: return deserialized # type: ignore @overload - async def create( - self, knowledge_source: _models2.KnowledgeSource, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source. + async def create_skillset( + self, skillset: _models2.SearchIndexerSkillset, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, knowledge_source: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source. + async def create_skillset( + self, skillset: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: JSON + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, knowledge_source: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source. + async def create_skillset( + self, skillset: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Required. - :type knowledge_source: IO[bytes] + :param skillset: The skillset containing one or more skills to create in a search service. + Required. + :type skillset: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "content_type", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - async def create( - self, knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source. + async def create_skillset( + self, skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.SearchIndexerSkillset: + """Creates a new skillset in a search service. - :param knowledge_source: The definition of the knowledge source to create. Is one of the - following types: KnowledgeSource, JSON, IO[bytes] Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource or JSON or + :param skillset: The skillset containing one or more skills to create in a search service. Is + one of the following types: SearchIndexerSkillset, JSON, IO[bytes] Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset or JSON or IO[bytes] - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5294,16 +5081,16 @@ async def create( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) + cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_source, (IOBase, bytes)): - _content = knowledge_source + if isinstance(skillset, (IOBase, bytes)): + _content = skillset else: - _content = json.dumps(knowledge_source, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(skillset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_sources_create_request( + _request = build_search_indexer_create_skillset_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -5316,7 +5103,7 @@ async def create( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5335,24 +5122,93 @@ async def create( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeSource, response.json()) + deserialized = _deserialize(_models2.SearchIndexerSkillset, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + async def reset_skills( + self, + skillset_name: str, + skill_names: _models2.SkillNames, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ -class _SearchIndexClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchIndexClientConfiguration] -): + @overload + async def reset_skills( + self, skillset_name: str, skill_names: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def reset_skills( + self, skillset_name: str, skill_names: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Required. + :type skill_names: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceStatistics: - """Gets service level statistics for a search service. + @api_version_validation( + method_added_on="2025-08-01-preview", + params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, + api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], + ) + async def reset_skills( + self, skillset_name: str, skill_names: Union[_models2.SkillNames, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Reset an existing skillset in a search service. - :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchServiceStatistics + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skill_names: The names of the skills to reset. If not specified, all skills in the + skillset will be reset. Is one of the following types: SkillNames, JSON, IO[bytes] Required. + :type skill_names: ~azure.search.documents.indexes.models.SkillNames or JSON or IO[bytes] + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5363,13 +5219,24 @@ async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceS } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.SearchServiceStatistics] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(skill_names, (IOBase, bytes)): + _content = skill_names + else: + _content = json.dumps(skill_names, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_get_service_statistics_request( + _request = build_search_indexer_reset_skills_request( + skillset_name=skillset_name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -5378,118 +5245,17 @@ async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceS } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize(_models3.ErrorResponse, response) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SearchServiceStatistics, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) - def get_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: - """Retrieves a summary of statistics for all indexes in the search service. - - :return: An iterator like instance of IndexStatisticsSummary - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.IndexStatisticsSummary] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models2.IndexStatisticsSummary]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_index_get_index_stats_summary_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models2.IndexStatisticsSummary], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py deleted file mode 100644 index 6b1532241601..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/operations/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import DataSourcesOperations # type: ignore -from ._operations import IndexersOperations # type: ignore -from ._operations import SkillsetsOperations # type: ignore -from ._operations import SynonymMapsOperations # type: ignore -from ._operations import IndexesOperations # type: ignore -from ._operations import AliasesOperations # type: ignore -from ._operations import AgentsOperations # type: ignore -from ._operations import SourcesOperations # type: ignore -from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataSourcesOperations", - "IndexersOperations", - "SkillsetsOperations", - "SynonymMapsOperations", - "IndexesOperations", - "AliasesOperations", - "AgentsOperations", - "SourcesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py index aa58ae78fc31..e8a411dd0c58 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py @@ -18,8 +18,8 @@ AIServicesAccountKey, AIServicesVisionParameters, AIServicesVisionVectorizer, - AnalyzeRequest, AnalyzeResult, + AnalyzeTextOptions, AnalyzedTokenInfo, AsciiFoldingTokenFilter, AzureActiveDirectoryApplicationCredentials, @@ -151,7 +151,7 @@ SearchIndexerDataContainer, SearchIndexerDataIdentity, SearchIndexerDataNoneIdentity, - SearchIndexerDataSource, + SearchIndexerDataSourceConnection, SearchIndexerDataUserAssignedIdentity, SearchIndexerError, SearchIndexerIndexProjection, @@ -298,8 +298,8 @@ "AIServicesAccountKey", "AIServicesVisionParameters", "AIServicesVisionVectorizer", - "AnalyzeRequest", "AnalyzeResult", + "AnalyzeTextOptions", "AnalyzedTokenInfo", "AsciiFoldingTokenFilter", "AzureActiveDirectoryApplicationCredentials", @@ -431,7 +431,7 @@ "SearchIndexerDataContainer", "SearchIndexerDataIdentity", "SearchIndexerDataNoneIdentity", - "SearchIndexerDataSource", + "SearchIndexerDataSourceConnection", "SearchIndexerDataUserAssignedIdentity", "SearchIndexerError", "SearchIndexerIndexProjection", diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 4cef621fc010..acb3d159f0af 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -346,40 +346,68 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AnalyzeRequest(_Model): +class AnalyzeResult(_Model): + """The result of testing an analyzer on text. + + :ivar tokens: The list of tokens returned by the analyzer specified in the request. Required. + :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] + """ + + tokens: list["_models.AnalyzedTokenInfo"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The list of tokens returned by the analyzer specified in the request. Required.""" + + @overload + def __init__( + self, + *, + tokens: list["_models.AnalyzedTokenInfo"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AnalyzeTextOptions(_Model): """Specifies some text and analysis components used to break that text into tokens. :ivar text: The text to break into tokens. Required. :vartype text: str - :ivar analyzer: The name of the analyzer to use to break the given text. If this parameter is - not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are - mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", - "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", - "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", - "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", - "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", - "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", - "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", - "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", - "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", - "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", - "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", - "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", - "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", - "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", - "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", - "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and - "whitespace". - :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar tokenizer: The name of the tokenizer to use to break the given text. If this parameter is - not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters are - mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", "letter", - "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", - "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". - :vartype tokenizer: str or ~azure.search.documents.indexes.models.LexicalTokenizerName - :ivar normalizer: The name of the normalizer to use to normalize the given text. Known values - are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :ivar analyzer_name: The name of the analyzer to use to break the given text. If this parameter + is not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters + are mutually exclusive. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", + "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", + "zh-Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", + "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", + "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", + "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", + "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", + "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", + "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", + "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", + "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", + "pt-PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", + "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", + "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", + "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", + "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", + "simple", "stop", and "whitespace". + :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar tokenizer_name: The name of the tokenizer to use to break the given text. If this + parameter is not specified, you must specify an analyzer instead. The tokenizer and analyzer + parameters are mutually exclusive. Known values are: "classic", "edgeNGram", "keyword_v2", + "letter", "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", + "nGram", "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", and "whitespace". + :vartype tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName + :ivar normalizer_name: The name of the normalizer to use to normalize the given text. Known + values are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". + :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName :ivar token_filters: An optional list of token filters to use when breaking the given text. This parameter can only be set when using the tokenizer parameter. :vartype token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] @@ -390,8 +418,8 @@ class AnalyzeRequest(_Model): text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The text to break into tokens. Required.""" - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="analyzer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the analyzer to use to break the given text. If this parameter is not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are mutually @@ -415,8 +443,8 @@ class AnalyzeRequest(_Model): \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" - tokenizer: Optional[Union[str, "_models.LexicalTokenizerName"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + tokenizer_name: Optional[Union[str, "_models.LexicalTokenizerName"]] = rest_field( + name="tokenizer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the tokenizer to use to break the given text. If this parameter is not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters are mutually @@ -424,8 +452,8 @@ class AnalyzeRequest(_Model): \"lowercase\", \"microsoft_language_tokenizer\", \"microsoft_language_stemming_tokenizer\", \"nGram\", \"path_hierarchy_v2\", \"pattern\", \"standard_v2\", \"uax_url_email\", and \"whitespace\".""" - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( + name="normalizer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the normalizer to use to normalize the given text. Known values are: \"asciifolding\", \"elision\", \"lowercase\", \"standard\", and \"uppercase\".""" @@ -445,9 +473,9 @@ def __init__( self, *, text: str, - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - tokenizer: Optional[Union[str, "_models.LexicalTokenizerName"]] = None, - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + tokenizer_name: Optional[Union[str, "_models.LexicalTokenizerName"]] = None, + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, token_filters: Optional[list[Union[str, "_models.TokenFilterName"]]] = None, char_filters: Optional[list[Union[str, "_models.CharFilterName"]]] = None, ) -> None: ... @@ -463,34 +491,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AnalyzeResult(_Model): - """The result of testing an analyzer on text. - - :ivar tokens: The list of tokens returned by the analyzer specified in the request. Required. - :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] - """ - - tokens: list["_models.AnalyzedTokenInfo"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The list of tokens returned by the analyzer specified in the request. Required.""" - - @overload - def __init__( - self, - *, - tokens: list["_models.AnalyzedTokenInfo"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class TokenFilter(_Model): """Base type for token filters. @@ -5803,10 +5803,11 @@ class ListDataSourcesResult(_Model): all datasources. :ivar data_sources: The datasources in the Search service. Required. - :vartype data_sources: list[~azure.search.documents.indexes.models.SearchIndexerDataSource] + :vartype data_sources: + list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] """ - data_sources: list["_models.SearchIndexerDataSource"] = rest_field( + data_sources: list["_models.SearchIndexerDataSourceConnection"] = rest_field( name="value", visibility=["read", "create", "update", "delete", "query"] ) """The datasources in the Search service. Required.""" @@ -5815,7 +5816,7 @@ class ListDataSourcesResult(_Model): def __init__( self, *, - data_sources: list["_models.SearchIndexerDataSource"], + data_sources: list["_models.SearchIndexerDataSourceConnection"], ) -> None: ... @overload @@ -7585,8 +7586,8 @@ class SearchField(_Model): :ivar permission_filter: A value indicating whether the field should be used as a permission filter. Known values are: "userIds", "groupIds", and "rbacScope". :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter - :ivar analyzer: The name of the analyzer to use for the field. This option can be used only - with searchable fields and it can't be set together with either searchAnalyzer or + :ivar analyzer_name: The name of the analyzer to use for the field. This option can be used + only with searchable fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", @@ -7605,11 +7606,11 @@ class SearchField(_Model): "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and "whitespace". - :vartype analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar search_analyzer: The name of the analyzer used at search time for the field. This option - can be used only with searchable fields. It must be set together with indexAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. This + :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar search_analyzer_name: The name of the analyzer used at search time for the field. This + option can be used only with searchable fields. It must be set together with indexAnalyzer and + it cannot be set together with the analyzer option. This property cannot be set to the name of + a language analyzer; use the analyzer property instead if you need a language analyzer. This analyzer can be updated on an existing field. Must be null for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", @@ -7628,13 +7629,14 @@ class SearchField(_Model): "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and "whitespace". - :vartype search_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar index_analyzer: The name of the analyzer used at indexing time for the field. This option - can be used only with searchable fields. It must be set together with searchAnalyzer and it - cannot be set together with the analyzer option. This property cannot be set to the name of a - language analyzer; use the analyzer property instead if you need a language analyzer. Once the - analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known - values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", + :vartype search_analyzer_name: str or + ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar index_analyzer_name: The name of the analyzer used at indexing time for the field. This + option can be used only with searchable fields. It must be set together with searchAnalyzer and + it cannot be set together with the analyzer option. This property cannot be set to the name of + a language analyzer; use the analyzer property instead if you need a language analyzer. Once + the analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. + Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", @@ -7651,12 +7653,12 @@ class SearchField(_Model): "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and "whitespace". - :vartype index_analyzer: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName - :ivar normalizer: The name of the normalizer to use for the field. This option can be used only - with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it - cannot be changed for the field. Must be null for complex fields. Known values are: + :vartype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar normalizer_name: The name of the normalizer to use for the field. This option can be used + only with fields with filterable, sortable, or facetable enabled. Once the normalizer is + chosen, it cannot be changed for the field. Must be null for complex fields. Known values are: "asciifolding", "elision", "lowercase", "standard", and "uppercase". - :vartype normalizer: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName :ivar vector_search_dimensions: The dimensionality of the vector field. :vartype vector_search_dimensions: int :ivar vector_search_profile_name: The name of the vector search profile that specifies the @@ -7665,12 +7667,12 @@ class SearchField(_Model): :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" :vartype vector_encoding_format: str or ~azure.search.documents.indexes.models.VectorEncodingFormat - :ivar synonym_maps: A list of the names of synonym maps to associate with this field. This + :ivar synonym_map_names: A list of the names of synonym maps to associate with this field. This option can be used only with searchable fields. Currently only one synonym map per field is supported. Assigning a synonym map to a field ensures that query terms targeting that field are expanded at query-time using the rules in the synonym map. This attribute can be changed on existing fields. Must be null or an empty collection for complex fields. - :vartype synonym_maps: list[str] + :vartype synonym_map_names: list[str] :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty for simple fields. :vartype fields: list[~azure.search.documents.indexes.models.SearchField] @@ -7747,8 +7749,8 @@ class SearchField(_Model): ) """A value indicating whether the field should be used as a permission filter. Known values are: \"userIds\", \"groupIds\", and \"rbacScope\".""" - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + name="analyzer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the analyzer to use for the field. This option can be used only with searchable fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once the @@ -7772,7 +7774,7 @@ class SearchField(_Model): \"th.lucene\", \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" - search_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + search_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( name="searchAnalyzer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the analyzer used at search time for the field. This option can be used only with @@ -7799,7 +7801,7 @@ class SearchField(_Model): \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" - index_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( + index_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( name="indexAnalyzer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the analyzer used at indexing time for the field. This option can be used only with @@ -7826,8 +7828,8 @@ class SearchField(_Model): \"th.lucene\", \"tr.microsoft\", \"tr.lucene\", \"uk.microsoft\", \"ur.microsoft\", \"vi.microsoft\", \"standard.lucene\", \"standardasciifolding.lucene\", \"keyword\", \"pattern\", \"simple\", \"stop\", and \"whitespace\".""" - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = rest_field( + name="normalizer", visibility=["read", "create", "update", "delete", "query"] ) """The name of the normalizer to use for the field. This option can be used only with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it cannot be changed @@ -7846,7 +7848,7 @@ class SearchField(_Model): name="vectorEncoding", visibility=["read", "create", "update", "delete", "query"] ) """The encoding format to interpret the field contents. \"packedBit\"""" - synonym_maps: Optional[list[str]] = rest_field( + synonym_map_names: Optional[list[str]] = rest_field( name="synonymMaps", visibility=["read", "create", "update", "delete", "query"] ) """A list of the names of synonym maps to associate with this field. This option can be used only @@ -7874,14 +7876,14 @@ def __init__( sortable: Optional[bool] = None, facetable: Optional[bool] = None, permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = None, - analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - search_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - index_analyzer: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, - normalizer: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, + analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + search_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + index_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, + normalizer_name: Optional[Union[str, "_models.LexicalNormalizerName"]] = None, vector_search_dimensions: Optional[int] = None, vector_search_profile_name: Optional[str] = None, vector_encoding_format: Optional[Union[str, "_models.VectorEncodingFormat"]] = None, - synonym_maps: Optional[list[str]] = None, + synonym_map_names: Optional[list[str]] = None, fields: Optional[list["_models.SearchField"]] = None, ) -> None: ... @@ -8354,7 +8356,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.odata_type = "#Microsoft.Azure.Search.DataNoneIdentity" # type: ignore -class SearchIndexerDataSource(_Model): +class SearchIndexerDataSourceConnection(_Model): """Represents a datasource definition, which can be used to configure an indexer. :ivar name: The name of the datasource. Required. diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index 87676c65a8f0..dbd6cee799d0 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -8,8 +8,577 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Dict, List, Optional, Union +from ._models import ( + SearchField as _SearchField, + SearchIndexerDataSourceConnection as _SearchIndexerDataSourceConnection, + SearchIndexerDataContainer, + SearchIndexerDataIdentity, + SearchResourceEncryptionKey, + DataChangeDetectionPolicy, + DataDeletionDetectionPolicy, + DataSourceCredentials, +) +from ._enums import ( + LexicalAnalyzerName, + IndexerPermissionOption, + SearchFieldDataType, + PermissionFilter, + VectorEncodingFormat, +) -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +String = "Edm.String" +Int32 = "Edm.Int32" +Int64 = "Edm.Int64" +Single = "Edm.Single" +Double = "Edm.Double" +Boolean = "Edm.Boolean" +DateTimeOffset = "Edm.DateTimeOffset" +GeographyPoint = "Edm.GeographyPoint" +ComplexType = "Edm.ComplexType" + + +def Collection(typ: str) -> str: + return "Collection({})".format(typ) + + +class SearchField(_SearchField): + # pylint: disable=too-many-instance-attributes + """Represents a field in an index definition, which describes the name, data type, and search behavior of a field. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the field, which must be unique within the fields collection of the + index or parent field. Required. + :vartype name: str + :ivar type: The data type of the field. Required. Known values are: "Edm.String", "Edm.Int32", + "Edm.Int64", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.GeographyPoint", + "Edm.ComplexType", "Edm.Single", "Edm.Half", "Edm.Int16", "Edm.SByte", and "Edm.Byte". + :vartype type: str or ~azure.search.documents.indexes.models.SearchFieldDataType + :ivar key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type Edm.String. Key fields can be used to look up documents directly and update or delete + specific documents. Default is false for simple fields and null for complex fields. + :vartype key: bool + :ivar stored: An immutable value indicating whether the field will be persisted separately on + disk to be returned in a search result. You can disable this option if you don't plan to return + the field contents in a search response to save on storage overhead. This can only be set + during index creation and only for vector fields. This property cannot be changed for existing + fields or set as false for new fields. If this property is set as false, the property + 'hidden' must be set to true. This property must be true or unset for key fields, + for new fields, and for non-vector fields, and it must be null for complex fields. Disabling + this property will reduce index storage requirements. The default is true for vector fields. + :vartype stored: bool + :ivar searchable: A value indicating whether the field is full-text searchable. This means it + will undergo analysis such as word-breaking during indexing. If you set a searchable field to a + value like "sunny day", internally it will be split into the individual tokens "sunny" and + "day". This enables full-text searches for these terms. Fields of type Edm.String or + Collection(Edm.String) are searchable by default. This property must be false for simple fields + of other non-string data types, and it must be null for complex fields. Note: searchable fields + consume extra space in your index since Azure Cognitive Search will store an additional + tokenized version of the field value for full-text searches. If you want to save space in your + index and you don't need a field to be included in searches, set searchable to false. + :vartype searchable: bool + :ivar filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields of type + Edm.String or Collection(Edm.String) that are filterable do not undergo word-breaking, so + comparisons are for exact matches only. For example, if you set such a field f to "sunny day", + $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' will. This property + must be null for complex fields. Default is true for simple fields and null for complex fields. + :vartype filterable: bool + :ivar sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default Azure Cognitive Search sorts results by score, but in many experiences + users will want to sort by fields in the documents. A simple field can be sortable only if it + is single-valued (it has a single value in the scope of the parent document). Simple collection + fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex + collections are also multi-valued, and therefore cannot be sortable. This is true whether it's + an immediate parent field, or an ancestor field, that's the complex collection. Complex fields + cannot be sortable and the sortable property must be null for such fields. The default for + sortable is true for single-valued simple fields, false for multi-valued simple fields, and + null for complex fields. + :vartype sortable: bool + :ivar facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). This property must be null for complex fields. Fields of type Edm.GeographyPoint or + Collection(Edm.GeographyPoint) cannot be facetable. Default is true for all other simple + fields. + :vartype facetable: bool + :ivar permission_filter: A value indicating whether the field should be used as a permission + filter. Known values are: "userIds", "groupIds", and "rbacScope". + :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter + :ivar analyzer_name: The name of the analyzer to use for the field. This option can be used only + with searchable fields and it can't be set together with either searchAnalyzer or + indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null + for complex fields. Known values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", + "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar search_analyzer_name: The name of the analyzer used at search time for the field. This option + can be used only with searchable fields. It must be set together with indexAnalyzer and it + cannot be set together with the analyzer option. This property cannot be set to the name of a + language analyzer; use the analyzer property instead if you need a language analyzer. This + analyzer can be updated on an existing field. Must be null for complex fields. Known values + are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", + "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", "zh-Hans.lucene", + "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", + "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", + "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", + "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", + "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", + "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", + "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", + "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", + "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar index_analyzer_name: The name of the analyzer used at indexing time for the field. This option + can be used only with searchable fields. It must be set together with searchAnalyzer and it + cannot be set together with the analyzer option. This property cannot be set to the name of a + language analyzer; use the analyzer property instead if you need a language analyzer. Once the + analyzer is chosen, it cannot be changed for the field. Must be null for complex fields. Known + values are: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", + "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh-Hans.microsoft", + "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", + "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", + "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", + "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", + "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", + "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", + "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", + "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", + "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt-PT.microsoft", + "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", + "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", + "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", + "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", + "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", and + "whitespace". + :vartype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :ivar normalizer_name: The name of the normalizer to use for the field. This option can be used only + with fields with filterable, sortable, or facetable enabled. Once the normalizer is chosen, it + cannot be changed for the field. Must be null for complex fields. Known values are: + "asciifolding", "elision", "lowercase", "standard", and "uppercase". + :vartype normalizer_name: str or ~azure.search.documents.indexes.models.LexicalNormalizerName + :ivar vector_search_dimensions: The dimensionality of the vector field. + :vartype vector_search_dimensions: int + :ivar vector_search_profile_name: The name of the vector search profile that specifies the algorithm + to use when searching the vector field. + :vartype vector_search_profile_name: str + :ivar synonym_map_names: A list of the names of synonym maps to associate with this field. This + option can be used only with searchable fields. Currently only one synonym map per field is + supported. Assigning a synonym map to a field ensures that query terms targeting that field are + expanded at query-time using the rules in the synonym map. This attribute can be changed on + existing fields. Must be null or an empty collection for complex fields. + :vartype synonym_map_names: list[str] + :ivar fields: A list of sub-fields if this is a field of type Edm.ComplexType or + Collection(Edm.ComplexType). Must be null or empty for simple fields. + :vartype fields: list[~azure.search.documents.indexes.models.SearchField] + :ivar vector_encoding_format: The encoding format to interpret the field contents. "packedBit" + :vartype vector_encoding_format: str or ~azure.search.documents.indexes.models.VectorEncodingFormat + """ + + def __init__( + self, + *, + name: str, + type: Union[str, SearchFieldDataType], + key: Optional[bool] = None, + hidden: Optional[bool] = None, + stored: Optional[bool] = None, + searchable: Optional[bool] = None, + filterable: Optional[bool] = None, + sortable: Optional[bool] = None, + facetable: Optional[bool] = None, + permission_filter: Optional[Union[str, PermissionFilter]] = None, + analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + synonym_map_names: Optional[List[str]] = None, + fields: Optional[List["SearchField"]] = None, + normalizer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + vector_search_dimensions: Optional[int] = None, + vector_search_profile_name: Optional[str] = None, + vector_encoding_format: Optional[Union[str, VectorEncodingFormat]] = None, + **kwargs + ): + retrievable = not hidden if hidden is not None else None + super().__init__( + name=name, + type=type, + key=key, + retrievable=retrievable, + stored=stored, + searchable=searchable, + filterable=filterable, + sortable=sortable, + facetable=facetable, + permission_filter=permission_filter, + analyzer_name=analyzer_name, + search_analyzer_name=search_analyzer_name, + index_analyzer_name=index_analyzer_name, + synonym_map_names=synonym_map_names, + fields=fields, + normalizer_name=normalizer_name, + vector_search_dimensions=vector_search_dimensions, + vector_search_profile_name=vector_search_profile_name, + vector_encoding_format=vector_encoding_format, + **kwargs + ) + + +def SimpleField( + *, + name: str, + type: str, + key: bool = False, + hidden: bool = False, + filterable: bool = False, + sortable: bool = False, + facetable: bool = False, + **kw # pylint:disable=unused-argument +) -> _SearchField: + """Configure a simple field for an Azure Search Index + + :keyword name: Required. The name of the field, which must be unique within the fields collection + of the index or parent field. + :paramtype name: str + :keyword type: Required. The data type of the field. Possible values include: SearchFieldDataType.String, + SearchFieldDataType.Int32, SearchFieldDataType.Int64, SearchFieldDataType.Double, SearchFieldDataType.Boolean, + SearchFieldDataType.DateTimeOffset, SearchFieldDataType.GeographyPoint, SearchFieldDataType.ComplexType, + from `azure.search.documents.SearchFieldDataType`. + :paramtype type: str + :keyword key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type SearchFieldDataType.String. Key fields can be used to look up documents directly and + update or delete specific documents. Default is False + :paramtype key: bool + :keyword hidden: A value indicating whether the field can be returned in a search result. + You can enable this option if you want to use a field (for example, margin) as a filter, + sorting, or scoring mechanism but do not want the field to be visible to the end user. This + property must be False for key fields. This property can be changed on existing fields. + Enabling this property does not cause any increase in index storage requirements. Default is + False. + :paramtype hidden: bool + :keyword filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields of type + SearchFieldDataType.String or Collection(SearchFieldDataType.String) that are filterable do + not undergo word-breaking, so comparisons are for exact matches only. For example, if you + set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but + $filter=f eq 'sunny day' will. This property must be null for complex fields. Default is False + :paramtype filterable: bool + :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default Azure Cognitive Search sorts results by score, but in many experiences + users will want to sort by fields in the documents. A simple field can be sortable only if it + is single-valued (it has a single value in the scope of the parent document). Simple collection + fields cannot be sortable, since they are multi-valued. Simple sub-fields of complex + collections are also multi-valued, and therefore cannot be sortable. This is true whether it's + an immediate parent field, or an ancestor field, that's the complex collection. The default is + False. + :paramtype sortable: bool + :keyword facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). Fields of type SearchFieldDataType.GeographyPoint or + Collection(SearchFieldDataType.GeographyPoint) cannot be facetable. Default is False. + :paramtype facetable: bool + :return: The search field object. + :rtype: SearchField + """ + result: Dict[str, Any] = { + "name": name, + "type": type, + "key": key, + "searchable": False, + "filterable": filterable, + "facetable": facetable, + "sortable": sortable, + "hidden": hidden, + } + return SearchField(**result) + + +def SearchableField( + *, + name: str, + collection: bool = False, + key: bool = False, + hidden: bool = False, + searchable: bool = True, + filterable: bool = False, + sortable: bool = False, + facetable: bool = False, + analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + search_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + index_analyzer_name: Optional[Union[str, LexicalAnalyzerName]] = None, + synonym_map_names: Optional[List[str]] = None, + **kw # pylint:disable=unused-argument +) -> SearchField: + """Configure a searchable text field for an Azure Search Index + + :keyword name: Required. The name of the field, which must be unique within the fields collection + of the index or parent field. + :paramtype name: str + :keyword collection: Whether this search field is a collection (default False) + :paramtype collection: bool + :keyword key: A value indicating whether the field uniquely identifies documents in the index. + Exactly one top-level field in each index must be chosen as the key field and it must be of + type SearchFieldDataType.String. Key fields can be used to look up documents directly and update or delete + specific documents. Default is False + :paramtype key: bool + :keyword hidden: A value indicating whether the field can be returned in a search result. + You can enable this option if you want to use a field (for example, margin) as a filter, + sorting, or scoring mechanism but do not want the field to be visible to the end user. This + property must be False for key fields. This property can be changed on existing fields. + Enabling this property does not cause any increase in index storage requirements. Default is + False. + :paramtype hidden: bool + :keyword searchable: A value indicating whether the field is full-text searchable. This means it + will undergo analysis such as word-breaking during indexing. If you set a searchable field to a + value like "sunny day", internally it will be split into the individual tokens "sunny" and + "day". This enables full-text searches for these terms. Note: searchable fields + consume extra space in your index since Azure Cognitive Search will store an additional + tokenized version of the field value for full-text searches. If you want to save space in your + index and you don't need a field to be included in searches, set searchable to false. Default + is True. + :paramtype searchable: bool + :keyword filterable: A value indicating whether to enable the field to be referenced in $filter + queries. filterable differs from searchable in how strings are handled. Fields that are + filterable do not undergo word-breaking, so comparisons are for exact matches only. For example, + if you set such a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but + $filter=f eq 'sunny day' will. Default is False. + :paramtype filterable: bool + :keyword sortable: A value indicating whether to enable the field to be referenced in $orderby + expressions. By default Azure Cognitive Search sorts results by score, but in many experiences + users will want to sort by fields in the documents. The default is False. + :paramtype sortable: bool + :keyword facetable: A value indicating whether to enable the field to be referenced in facet + queries. Typically used in a presentation of search results that includes hit count by category + (for example, search for digital cameras and see hits by brand, by megapixels, by price, and so + on). Default is False. + :paramtype facetable: bool + :keyword analyzer_name: The name of the analyzer to use for the field. This option can't be set together + with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed + for the field. Possible values include: 'ar.microsoft', 'ar.lucene', 'hy.lucene', + 'bn.microsoft', 'eu.lucene', 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh- + Hans.microsoft', 'zh-Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', + 'cs.microsoft', 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', + 'en.microsoft', 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', + 'fr.lucene', 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', + 'gu.microsoft', 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', + 'is.microsoft', 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', + 'ja.microsoft', 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', + 'lv.lucene', 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', + 'no.lucene', 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt- + PT.microsoft', 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', + 'ru.lucene', 'sr-cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', + 'es.microsoft', 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', + 'th.microsoft', 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', + 'vi.microsoft', 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', + 'simple', 'stop', 'whitespace'. + :paramtype analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :keyword search_analyzer_name: The name of the analyzer used at search time for the field. It must be + set together with indexAnalyzer and it cannot be set together with the analyzer option. This + property cannot be set to the name of a language analyzer; use the analyzer property instead + if you need a language analyzer. This analyzer can be updated on an existing field. Possible + values include: + 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', 'bg.microsoft', + 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh-Hans.lucene', 'zh- + Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', 'cs.lucene', 'da.microsoft', + 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', 'en.lucene', 'et.microsoft', + 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', 'gl.lucene', 'de.microsoft', + 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', 'he.microsoft', 'hi.microsoft', + 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', 'id.microsoft', 'id.lucene', + 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', 'ja.lucene', 'kn.microsoft', + 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', 'lt.microsoft', 'ml.microsoft', + 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', 'fa.lucene', 'pl.microsoft', + 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', 'pt-PT.lucene', + 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- + cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', + 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', + 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', + 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', + 'whitespace'. + :paramtype search_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :keyword index_analyzer_name: The name of the analyzer used at indexing time for the field. + It must be set together with searchAnalyzer and it cannot be set together with the analyzer + option. This property cannot be set to the name of a language analyzer; use the analyzer + property instead if you need a language analyzer. Once the analyzer is chosen, it cannot be + changed for the field. Possible values include: + 'ar.microsoft', 'ar.lucene', 'hy.lucene', 'bn.microsoft', 'eu.lucene', + 'bg.microsoft', 'bg.lucene', 'ca.microsoft', 'ca.lucene', 'zh-Hans.microsoft', 'zh- + Hans.lucene', 'zh-Hant.microsoft', 'zh-Hant.lucene', 'hr.microsoft', 'cs.microsoft', + 'cs.lucene', 'da.microsoft', 'da.lucene', 'nl.microsoft', 'nl.lucene', 'en.microsoft', + 'en.lucene', 'et.microsoft', 'fi.microsoft', 'fi.lucene', 'fr.microsoft', 'fr.lucene', + 'gl.lucene', 'de.microsoft', 'de.lucene', 'el.microsoft', 'el.lucene', 'gu.microsoft', + 'he.microsoft', 'hi.microsoft', 'hi.lucene', 'hu.microsoft', 'hu.lucene', 'is.microsoft', + 'id.microsoft', 'id.lucene', 'ga.lucene', 'it.microsoft', 'it.lucene', 'ja.microsoft', + 'ja.lucene', 'kn.microsoft', 'ko.microsoft', 'ko.lucene', 'lv.microsoft', 'lv.lucene', + 'lt.microsoft', 'ml.microsoft', 'ms.microsoft', 'mr.microsoft', 'nb.microsoft', 'no.lucene', + 'fa.lucene', 'pl.microsoft', 'pl.lucene', 'pt-BR.microsoft', 'pt-BR.lucene', 'pt-PT.microsoft', + 'pt-PT.lucene', 'pa.microsoft', 'ro.microsoft', 'ro.lucene', 'ru.microsoft', 'ru.lucene', 'sr- + cyrillic.microsoft', 'sr-latin.microsoft', 'sk.microsoft', 'sl.microsoft', 'es.microsoft', + 'es.lucene', 'sv.microsoft', 'sv.lucene', 'ta.microsoft', 'te.microsoft', 'th.microsoft', + 'th.lucene', 'tr.microsoft', 'tr.lucene', 'uk.microsoft', 'ur.microsoft', 'vi.microsoft', + 'standard.lucene', 'standardasciifolding.lucene', 'keyword', 'pattern', 'simple', 'stop', + 'whitespace'. + :paramtype index_analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName + :keyword synonym_map_names: A list of the names of synonym maps to associate with this field. Currently + only one synonym map per field is supported. Assigning a synonym map to a field ensures that + query terms targeting that field are expanded at query-time using the rules in the synonym map. + This attribute can be changed on existing fields. + :paramtype synonym_map_names: list[str] + :return: The search field object. + :rtype: SearchField + """ + typ = Collection(String) if collection else String + result: Dict[str, Any] = { + "name": name, + "type": typ, + "key": key, + "searchable": searchable, + "filterable": filterable, + "facetable": facetable, + "sortable": sortable, + "hidden": hidden, + } + if analyzer_name: + result["analyzer_name"] = analyzer_name + if search_analyzer_name: + result["search_analyzer_name"] = search_analyzer_name + if index_analyzer_name: + result["index_analyzer_name"] = index_analyzer_name + if synonym_map_names: + result["synonym_map_names"] = synonym_map_names + return SearchField(**result) + + +def ComplexField( + *, + name: str, + collection: bool = False, + fields: Optional[List[_SearchField]] = None, + **kw # pylint:disable=unused-argument +) -> _SearchField: + """Configure a Complex or Complex collection field for an Azure Search Index + + :keyword name: Required. The name of the field, which must be unique within the fields collection + of the index or parent field. + :paramtype name: str + :keyword collection: Whether this complex field is a collection (default False) + :paramtype collection: bool + :keyword fields: A list of sub-fields + :paramtype fields: list[~azure.search.documents.indexes.models.SearchField] + :return: The search field object. + :rtype: SearchField + """ + typ = Collection(ComplexType) if collection else ComplexType + result: Dict[str, Any] = {"name": name, "type": typ, "fields": fields} + return _SearchField(**result) + + +class SearchIndexerDataSourceConnection(_SearchIndexerDataSourceConnection): + """Represents a datasource connection definition, which can be used to configure an indexer. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. The name of the datasource connection. + :vartype name: str + :ivar description: The description of the datasource connection. + :vartype description: str + :ivar type: Required. The type of the datasource connection. Possible values include: "azuresql", + "cosmosdb", "azureblob", "azuretable", "mysql", "adlsgen2". + :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType + :ivar connection_string: The connection string for the datasource connection. + :vartype connection_string: str + :ivar container: Required. The data container for the datasource connection. + :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer + :ivar identity: An explicit managed identity to use for this datasource. If not specified and + the connection string is a managed identity, the system-assigned managed identity is used. If + not specified, the value remains unchanged. If "none" is specified, the value of this property + is cleared. + :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity + :ivar indexer_permission_options: Ingestion options with various types of permission data. + :vartype indexer_permission_options: list[str or + ~azure.search.documents.indexes.models.IndexerPermissionOption] + :ivar data_change_detection_policy: The data change detection policy for the datasource connection. + :vartype data_change_detection_policy: ~azure.search.documents.models.DataChangeDetectionPolicy + :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource connection. + :vartype data_deletion_detection_policy: + ~azure.search.documents.models.DataDeletionDetectionPolicy + :ivar e_tag: The ETag of the data source. + :vartype e_tag: str + :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your datasource + definition when you want full assurance that no one, not even Microsoft, can decrypt your data + source definition in Azure Cognitive Search. Once you have encrypted your data source + definition, it will always remain encrypted. Azure Cognitive Search will ignore attempts to set + this property to null. You can change this property as needed if you want to rotate your + encryption key; Your datasource definition will be unaffected. Encryption with customer-managed + keys is not available for free search services, and is only available for paid services created + on or after January 1, 2019. + :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey + """ + + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + type: str, + connection_string: str, + container: SearchIndexerDataContainer, + identity: Optional[SearchIndexerDataIdentity] = None, + indexer_permission_options: Optional[List[Union[str, IndexerPermissionOption]]] = None, + data_change_detection_policy: Optional[DataChangeDetectionPolicy] = None, + data_deletion_detection_policy: Optional[DataDeletionDetectionPolicy] = None, + e_tag: Optional[str] = None, + encryption_key: Optional[SearchResourceEncryptionKey] = None, + **kwargs + ): + credentials = DataSourceCredentials(connection_string=connection_string) + super().__init__( + name=name, + description=description, + type=type, + credentials=credentials, + container=container, + data_change_detection_policy=data_change_detection_policy, + data_deletion_detection_policy=data_deletion_detection_policy, + e_tag=e_tag, + encryption_key=encryption_key, + identity=identity, + indexer_permission_options=indexer_permission_options, + **kwargs + ) + + +__all__: list[str] = [ + "SearchField", + "SimpleField", + "SearchableField", + "ComplexField", + "SearchIndexerDataSourceConnection", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py deleted file mode 100644 index 6b1532241601..000000000000 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/operations/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import DataSourcesOperations # type: ignore -from ._operations import IndexersOperations # type: ignore -from ._operations import SkillsetsOperations # type: ignore -from ._operations import SynonymMapsOperations # type: ignore -from ._operations import IndexesOperations # type: ignore -from ._operations import AliasesOperations # type: ignore -from ._operations import AgentsOperations # type: ignore -from ._operations import SourcesOperations # type: ignore -from ._operations import _SearchIndexClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DataSourcesOperations", - "IndexersOperations", - "SkillsetsOperations", - "SynonymMapsOperations", - "IndexesOperations", - "AliasesOperations", - "AgentsOperations", - "SourcesOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py index e701aa5d5822..fcb1e21616ec 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_client.py @@ -17,17 +17,15 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import KnowledgeBaseRetrievalClientConfiguration -from .operations import KnowledgeRetrievalOperations +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin if TYPE_CHECKING: from azure.core.credentials import TokenCredential -class KnowledgeBaseRetrievalClient: +class KnowledgeBaseRetrievalClient(_KnowledgeBaseRetrievalClientOperationsMixin): """KnowledgeBaseRetrievalClient. - :ivar knowledge_retrieval: KnowledgeRetrievalOperations operations - :vartype knowledge_retrieval: azure.search.documents.operations.KnowledgeRetrievalOperations :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -66,9 +64,6 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCr self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.knowledge_retrieval = KnowledgeRetrievalOperations( - self._client, self._config, self._serialize, self._deserialize - ) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/__init__.py similarity index 86% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/__init__.py index 48bd23b4f6a7..6d56cb9d9b3f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/__init__.py @@ -12,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import KnowledgeRetrievalOperations # type: ignore +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "KnowledgeRetrievalOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py similarity index 91% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py index f353833f4cb9..dd6310f3cedb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py @@ -28,20 +28,20 @@ from .. import models as _models1 from ..._utils.model_base import SdkJSONEncoder, _deserialize -from ..._utils.serialization import Deserializer, Serializer +from ..._utils.serialization import Serializer +from ..._utils.utils import ClientMixinABC from ..._validation import api_version_validation from .._configuration import KnowledgeBaseRetrievalClientConfiguration JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_knowledge_retrieval_retrieve_request( # pylint: disable=name-too-long +def build_knowledge_base_retrieval_retrieve_request( # pylint: disable=name-too-long knowledge_base_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -74,24 +74,9 @@ def build_knowledge_retrieval_retrieve_request( # pylint: disable=name-too-long return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class KnowledgeRetrievalOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.KnowledgeBaseRetrievalClient`'s - :attr:`knowledge_retrieval` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: KnowledgeBaseRetrievalClientConfiguration = ( - input_args.pop(0) if input_args else kwargs.pop("config") - ) - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _KnowledgeBaseRetrievalClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], KnowledgeBaseRetrievalClientConfiguration] +): @overload def retrieve( @@ -242,7 +227,7 @@ def retrieve( else: _content = json.dumps(retrieval_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_knowledge_retrieval_retrieve_request( + _request = build_knowledge_base_retrieval_retrieve_request( knowledge_base_name=knowledge_base_name, query_source_authorization=query_source_authorization, content_type=content_type, diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebase/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py index f6cc4b139bb1..0bbbb8cd4366 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_client.py @@ -17,18 +17,15 @@ from ..._utils.serialization import Deserializer, Serializer from ._configuration import KnowledgeBaseRetrievalClientConfiguration -from .operations import KnowledgeRetrievalOperations +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class KnowledgeBaseRetrievalClient: +class KnowledgeBaseRetrievalClient(_KnowledgeBaseRetrievalClientOperationsMixin): """KnowledgeBaseRetrievalClient. - :ivar knowledge_retrieval: KnowledgeRetrievalOperations operations - :vartype knowledge_retrieval: - azure.search.documents.aio.operations.KnowledgeRetrievalOperations :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -69,9 +66,6 @@ def __init__( self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.knowledge_retrieval = KnowledgeRetrievalOperations( - self._client, self._config, self._serialize, self._deserialize - ) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/__init__.py similarity index 86% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/__init__.py index 48bd23b4f6a7..6d56cb9d9b3f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/__init__.py @@ -12,14 +12,12 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import KnowledgeRetrievalOperations # type: ignore +from ._operations import _KnowledgeBaseRetrievalClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [ - "KnowledgeRetrievalOperations", -] +__all__ = [] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py similarity index 89% rename from sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py index e0ff63ac5b1e..0cab3bd0412e 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -28,35 +29,19 @@ from ... import models as _models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize -from ...._utils.serialization import Deserializer, Serializer +from ...._utils.utils import ClientMixinABC from ...._validation import api_version_validation -from ...operations._operations import build_knowledge_retrieval_retrieve_request +from ..._operations._operations import build_knowledge_base_retrieval_retrieve_request from .._configuration import KnowledgeBaseRetrievalClientConfiguration JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -List = list -class KnowledgeRetrievalOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.search.documents.aio.KnowledgeBaseRetrievalClient`'s - :attr:`knowledge_retrieval` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: KnowledgeBaseRetrievalClientConfiguration = ( - input_args.pop(0) if input_args else kwargs.pop("config") - ) - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") +class _KnowledgeBaseRetrievalClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], KnowledgeBaseRetrievalClientConfiguration] +): @overload async def retrieve( @@ -207,7 +192,7 @@ async def retrieve( else: _content = json.dumps(retrieval_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_knowledge_retrieval_retrieve_request( + _request = build_knowledge_base_retrieval_retrieve_request( knowledge_base_name=knowledge_base_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -222,7 +207,7 @@ async def retrieve( _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_patch.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/operations/_patch.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index fda9f9667a56..bd774c1a79b5 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -922,10 +922,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class SearchRequest(_Model): """Parameters for filtering, sorting, faceting, paging, and other search query behaviors. - :ivar include_total_result_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. - :vartype include_total_result_count: bool + :ivar include_total_count: A value that specifies whether to fetch the total count of results. + Default is false. Setting this value to true may have a performance impact. Note that the count + returned is an approximation. + :vartype include_total_count: bool :ivar facets: The list of facet expressions to apply to the search query. Each facet expression contains a field name, optionally followed by a comma-separated list of name:value pairs. :vartype facets: list[str] @@ -1002,9 +1002,9 @@ class SearchRequest(_Model): "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". :vartype query_language: str or ~azure.search.documents.models.QueryLanguage - :ivar speller: A value that specified the type of the speller to use to spell-correct + :ivar query_speller: A value that specified the type of the speller to use to spell-correct individual search query terms. Known values are: "none" and "lexicon". - :vartype speller: str or ~azure.search.documents.models.QuerySpellerType + :vartype query_speller: str or ~azure.search.documents.models.QuerySpellerType :ivar select: The comma-separated list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included. :vartype select: str @@ -1017,9 +1017,9 @@ class SearchRequest(_Model): paging, the response will include a continuation token that can be used to issue another Search request for the next page of results. :vartype top: int - :ivar semantic_configuration: The name of a semantic configuration that will be used when + :ivar semantic_configuration_name: The name of a semantic configuration that will be used when processing documents for queries of type semantic. - :vartype semantic_configuration: str + :vartype semantic_configuration_name: str :ivar semantic_error_handling: Allows the user to choose whether a semantic call should fail completely (default / current behavior), or to return partial results. Known values are: "partial" and "fail". @@ -1053,7 +1053,7 @@ class SearchRequest(_Model): :vartype hybrid_search: ~azure.search.documents.models.HybridSearch """ - include_total_result_count: Optional[bool] = rest_field( + include_total_count: Optional[bool] = rest_field( name="count", visibility=["read", "create", "update", "delete", "query"] ) """A value that specifies whether to fetch the total count of results. Default is false. Setting @@ -1156,8 +1156,8 @@ class SearchRequest(_Model): \"et-ee\", \"ca-es\", \"fi-fi\", \"sr-ba\", \"sr-me\", \"sr-rs\", \"sk-sk\", \"nb-no\", \"hy-am\", \"bn-in\", \"eu-es\", \"gl-es\", \"gu-in\", \"he-il\", \"ga-ie\", \"kn-in\", \"ml-in\", \"mr-in\", \"fa-ae\", \"pa-in\", \"te-in\", and \"ur-pk\".""" - speller: Optional[Union[str, "_models.QuerySpellerType"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + query_speller: Optional[Union[str, "_models.QuerySpellerType"]] = rest_field( + name="speller", visibility=["read", "create", "update", "delete", "query"] ) """A value that specified the type of the speller to use to spell-correct individual search query terms. Known values are: \"none\" and \"lexicon\".""" @@ -1173,7 +1173,7 @@ class SearchRequest(_Model): implement client-side paging of search results. If results are truncated due to server-side paging, the response will include a continuation token that can be used to issue another Search request for the next page of results.""" - semantic_configuration: Optional[str] = rest_field( + semantic_configuration_name: Optional[str] = rest_field( name="semanticConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The name of a semantic configuration that will be used when processing documents for queries of @@ -1232,7 +1232,7 @@ class SearchRequest(_Model): def __init__( # pylint: disable=too-many-locals self, *, - include_total_result_count: Optional[bool] = None, + include_total_count: Optional[bool] = None, facets: Optional[list[str]] = None, filter: Optional[str] = None, # pylint: disable=redefined-builtin highlight_fields: Optional[str] = None, @@ -1250,11 +1250,11 @@ def __init__( # pylint: disable=too-many-locals search_fields: Optional[str] = None, search_mode: Optional[Union[str, "_models.SearchMode"]] = None, query_language: Optional[Union[str, "_models.QueryLanguage"]] = None, - speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, + query_speller: Optional[Union[str, "_models.QuerySpellerType"]] = None, select: Optional[str] = None, skip: Optional[int] = None, top: Optional[int] = None, - semantic_configuration: Optional[str] = None, + semantic_configuration_name: Optional[str] = None, semantic_error_handling: Optional[Union[str, "_models.SemanticErrorMode"]] = None, semantic_max_wait_in_milliseconds: Optional[int] = None, semantic_query: Optional[str] = None, diff --git a/sdk/search/azure-search-documents/samples/README.md b/sdk/search/azure-search-documents/samples/README.md new file mode 100644 index 000000000000..9a658a5cd783 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/README.md @@ -0,0 +1,73 @@ +--- +page_type: sample +languages: + - python +products: + - azure + - azure-search +--- + +# Samples for Azure Cognitive Search client library for Python + +These code samples show common scenario operations with the Azure Cognitive +Search client library. + +Authenticate the client with a Azure Cognitive Search [API Key Credential](https://learn.microsoft.com/azure/search/search-security-api-keys): + +[https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/search/azure-search-documents/samples/sample_authentication.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_authentication.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py)) + +Then for common search index operations: + +* Get a document by key: [sample_get_document.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_get_document.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py)) + +* Perform a simple text query: [sample_simple_query.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_simple_query.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py)) + +* Perform a filtered query: [sample_filter_query.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_filter_query.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py)) + +* Perform a faceted query: [sample_facet_query.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_facet_query.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py)) + +* Get auto-completions: [sample_autocomplete.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_autocomplete.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py)) + +* Get search suggestions: [sample_suggestions.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_suggestions.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py)) + +* Perform basic document updates: [sample_crud_operations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_crud_operations.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py)) + +* CRUD operations for index: [sample_index_crud_operations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py)) + +* Analyze text: [sample_analyze_text.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_analyze_text.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py)) + +* CRUD operations for indexers: [sample_indexers_operations.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_indexers_operations.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py)) + +* General workflow of indexer, datasource and index: [sample_indexer_datasource_skillset.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py) + +* Semantic search: [sample_semantic_search.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_semantic_search.py) + +* Vector search: [sample_vector_search.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_vector_search.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py)) + +## Prerequisites + +* Python 3.8 or later is required to use this package +* You must have an [Azure subscription](https://azure.microsoft.com/free/) +* You must create the "Hotels" sample index [in the Azure Portal](https://learn.microsoft.com/azure/search/search-get-started-portal) + +## Setup + +1. Install the Azure Cognitive Search client library for Python with [pip](https://pypi.org/project/pip/): + + ```bash + pip install azure-search-documents --pre + ``` + +2. Clone or download [this repository](https://github.com/Azure/azure-sdk-for-python) +3. Open this sample folder in [Visual Studio Code](https://code.visualstudio.com) or your IDE of choice. + +## Running the samples + +1. Open a terminal window and `cd` to the directory that the samples are saved in. +2. Set the environment variables specified in the sample file you wish to run. +3. Follow the usage described in the file, e.g. `python sample_simple_query.py` + +## Next steps + +Check out the [API reference documentation](https://learn.microsoft.com/rest/api/searchservice/) +to learn more about what you can do with the Azure Cognitive Search client library. diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py new file mode 100644 index 000000000000..a20a4d5cc4af --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_analyze_text_async.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_analyze_text_async.py +DESCRIPTION: + This sample demonstrates how to analyze text. +USAGE: + python sample_analyze_text_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def simple_analyze_text(): + # [START simple_analyze_text_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.indexes.aio import SearchIndexClient + from azure.search.documents.indexes.models import AnalyzeTextOptions + + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") + + async with client: + result = await client.analyze_text(index_name, analyze_request) + print(result.as_dict()) + # [END simple_analyze_text_async] + + +if __name__ == "__main__": + asyncio.run(simple_analyze_text()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py new file mode 100644 index 000000000000..e4340c96274c --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_authentication_async.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_authentication_async.py +DESCRIPTION: + This sample demonstrates how to authenticate with the Azure Congnitive Search + service with an API key. See more details about authentication here: + https://learn.microsoft.com/azure.search.documents/search-security-api-keys +USAGE: + python sample_authentication_async.py + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import asyncio +import os + + +async def authentication_with_api_key_credential_async(): + # [START create_search_client_with_key_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + # [END create_search_client_with_key_async] + + async with search_client: + result = await search_client.get_document_count() + + print("There are {} documents in the {} search index.".format(result, index_name)) + + +async def authentication_service_client_with_api_key_credential_async(): + # [START create_search_service_with_key_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.indexes.aio import SearchIndexClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + # [END create_search_service_with_key_async] + + +async def authentication_with_aad(): + # [START authentication_with_aad] + from azure.identity.aio import DefaultAzureCredential + from azure.search.documents.aio import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + credential = DefaultAzureCredential() + + search_client = SearchClient(service_endpoint, index_name, credential) + # [END authentication_with_aad] + + async with search_client: + result = await search_client.get_document_count() + + print("There are {} documents in the {} search index.".format(result, index_name)) + + +async def authentication_service_client_with_aad(): + # [START authentication_service_client_with_aad] + from azure.identity.aio import DefaultAzureCredential + from azure.search.documents.indexes.aio import SearchIndexClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + credential = DefaultAzureCredential() + + client = SearchIndexClient(service_endpoint, credential) + # [END authentication_service_client_with_aad] + + +if __name__ == "__main__": + asyncio.run(authentication_with_api_key_credential_async()) + asyncio.run(authentication_service_client_with_api_key_credential_async()) + asyncio.run(authentication_with_aad()) + asyncio.run(authentication_service_client_with_aad()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py new file mode 100644 index 000000000000..856652212a40 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_autocomplete_async.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_autocomplete_async.py +DESCRIPTION: + This sample demonstrates how to obtain autocompletion suggestions from an + Azure search index. +USAGE: + python sample_autocomplete_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def autocomplete_query(): + # [START autocomplete_query_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + results = await search_client.autocomplete(search_text="bo", suggester_name="sg") + + print("Autocomplete suggestions for 'bo'") + for result in results: + print(" Completion: {}".format(result["text"])) + # [END autocomplete_query_async] + + +if __name__ == "__main__": + asyncio.run(autocomplete_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py new file mode 100644 index 000000000000..23b9aeae146c --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_buffered_sender_async.py @@ -0,0 +1,56 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_batch_client_async.py +DESCRIPTION: + This sample demonstrates how to upload, merge, or delete documents using SearchIndexingBufferedSender. +USAGE: + python sample_batch_client_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.aio import SearchIndexingBufferedSender + + +async def sample_batching_client(): + DOCUMENT = { + "category": "Hotel", + "hotelId": "1000", + "rating": 4.0, + "rooms": [], + "hotelName": "Azure Inn", + } + + async with SearchIndexingBufferedSender(service_endpoint, index_name, AzureKeyCredential(key)) as batch_client: + # add upload actions + await batch_client.upload_documents(documents=[DOCUMENT]) + # add merge actions + await batch_client.merge_documents(documents=[{"hotelId": "1000", "rating": 4.5}]) + # add delete actions + await batch_client.delete_documents(documents=[{"hotelId": "1000"}]) + + +async def main(): + await sample_batching_client() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py new file mode 100644 index 000000000000..697d8d03ae10 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_crud_operations_async.py @@ -0,0 +1,73 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_crud_operations_async.py +DESCRIPTION: + This sample demonstrates how to upload, merge, or delete documents from an + Azure Search index. +USAGE: + python sample_crud_operations_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.aio import SearchClient + +search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + +async def upload_document(): + # [START upload_document_async] + DOCUMENT = { + "hotelId": "1000", + "hotelName": "Azure Inn", + } + + result = await search_client.upload_documents(documents=[DOCUMENT]) + + print("Upload of new document succeeded: {}".format(result[0].succeeded)) + # [END upload_document_async] + + +async def merge_document(): + # [START merge_document_async] + result = await search_client.upload_documents(documents=[{"hotelId": "783", "hotelName": "Renovated Ranch"}]) + + print("Merge into new document succeeded: {}".format(result[0].succeeded)) + # [END merge_document_async] + + +async def delete_document(): + # [START delete_document_async] + result = await search_client.upload_documents(documents=[{"hotelId": "1000"}]) + + print("Delete new document succeeded: {}".format(result[0].succeeded)) + # [END delete_document_async] + + +async def main(): + await upload_document() + await merge_document() + await delete_document() + await search_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py new file mode 100644 index 000000000000..fd39b24abbe8 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_data_source_operations_async.py @@ -0,0 +1,81 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_data_source_operations_async.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete a Data Source. +USAGE: + python sample_data_source_operations_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + +import asyncio +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] +connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.models import SearchIndexerDataContainer, SearchIndexerDataSourceConnection +from azure.search.documents.indexes.aio import SearchIndexerClient + +client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + + +async def create_data_source_connection(): + # [START create_data_source_connection_async] + container = SearchIndexerDataContainer(name="searchcontainer") + data_source = SearchIndexerDataSourceConnection( + name="async-sample-data-source-connection", + type="azureblob", + connection_string=connection_string, + container=container, + ) + result = await client.create_data_source_connection(data_source) + print("Create new Data Source Connection - async-sample-data-source-connection") + # [END create_data_source_connection_async] + + +async def list_data_source_connections(): + # [START list_data_source_connection_async] + result = await client.get_data_source_connections() + names = [x.name for x in result] + print("Found {} Data Source Connections in the service: {}".format(len(result), ", ".join(names))) + # [END list_data_source_connection_async] + + +async def get_data_source_connection(): + # [START get_data_source_connection_async] + result = await client.get_data_source_connection("async-sample-data-source-connection") + print("Retrived Data Source Connection 'async-sample-data-source-connection'") + return result + # [END get_data_source_connection_async] + + +async def delete_data_source_connection(): + # [START delete_data_source_connection_async] + await client.delete_data_source_connection("async-sample-data-source-connection") + print("Data Source Connection 'async-sample-data-source-connection' successfully deleted") + # [END delete_data_source_connection_async] + + +async def main(): + await create_data_source_connection() + await list_data_source_connections() + await get_data_source_connection() + await delete_data_source_connection() + await client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py new file mode 100644 index 000000000000..1ce8666eabbd --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_facet_query_async.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_facet_query_async.py +DESCRIPTION: + This sample demonstrates how to obtain search facets on specified field in + an Azure Search index. +USAGE: + python sample_facet_query_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +from typing import List, Dict, cast +import os +import asyncio + + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def filter_query(): + # [START facet_query_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + results = await search_client.search(search_text="WiFi", facets=["category,count:3", "parkingIncluded"]) + + facets: Dict[str, List[str]] = cast(Dict[str, List[str]], await results.get_facets()) + + print("Catgory facet counts for hotels:") + for facet in facets["category"]: + print(" {}".format(facet)) + # [END facet_query_async] + + +if __name__ == "__main__": + asyncio.run(filter_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py new file mode 100644 index 000000000000..e8dc44bda617 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_filter_query_async.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_filter_query_async.py +DESCRIPTION: + This sample demonstrates how search results from an Azure Search index can + be filtered and ordered. +USAGE: + python sample_filter_query_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def filter_query(): + # [START filter_query_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + results = await search_client.search( + search_text="WiFi", + filter="Address/StateProvince eq 'FL' and Address/Country eq 'USA'", + select=["hotelName", "rating"], + order_by=["rating desc"], + ) + + print("Florida hotels containing 'WiFi', sorted by Rating:") + async for result in results: + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) + # [END filter_query_async] + + +if __name__ == "__main__": + asyncio.run(filter_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py new file mode 100644 index 000000000000..c9b177bef4eb --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_get_document_async.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_document_async.py +DESCRIPTION: + This sample demonstrates how to retrieve a specific document by key from an + Azure Search index. +USAGE: + python sample_get_document_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def autocomplete_query(): + # [START get_document_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + result = await search_client.get_document(key="23") + + print("Details for hotel '23' are:") + print(" Name: {}".format(result["hotelName"])) + # [END get_document_async] + + +if __name__ == "__main__": + asyncio.run(autocomplete_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py new file mode 100644 index 000000000000..3a47a8fb8641 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_index_alias_crud_operations_async.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_index_alias_crud_operations_async.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete an alias with an existing index. +USAGE: + python sample_index_alias_crud_operations_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key + 3) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") +""" + + +import asyncio +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] +alias_name = "motels" + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.aio import SearchIndexClient +from azure.search.documents.indexes.models import ( + ComplexField, + CorsOptions, + ScoringProfile, + SearchAlias, + SearchIndex, + SimpleField, + SearchableField, + SearchFieldDataType, +) + + +client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + +async def create_alias(): + # [START create_alias_async] + alias = SearchAlias(name=alias_name, indexes=[index_name]) + result = await client.create_alias(alias) + # [END create_alias_async] + + +async def get_alias(): + # [START get_alias_async] + result = await client.get_alias(alias_name) + # [END get_alias_async] + + +async def update_alias(): + # [START update_alias_async] + new_index_name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + SearchableField(name="hotelName", type=SearchFieldDataType.String), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + SimpleField(name="state", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex( + name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options + ) + + result_index = await client.create_or_update_index(index=index) + + alias = SearchAlias(name=alias_name, indexes=[new_index_name]) + result = await client.create_or_update_alias(alias) + + # [END update_alias_async] + + +async def delete_alias(): + # [START delete_alias_async] + + await client.delete_alias(alias_name) + # [END delete_alias_async] + + +async def main(): + await create_alias() + await get_alias() + await update_alias() + await delete_alias() + await client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py new file mode 100644 index 000000000000..cd767d24f621 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_index_client_send_request_async.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_index_client_send_request_async.py + +DESCRIPTION: + This sample demonstrates how to make custom HTTP requests through a client pipeline. + +USAGE: + python sample_index_client_send_request_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import asyncio +import os +from azure.core.credentials import AzureKeyCredential +from azure.core.rest import HttpRequest +from azure.search.documents.indexes.aio import SearchIndexClient + + +async def sample_send_request(): + endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + client = SearchIndexClient(endpoint, AzureKeyCredential(key)) + + # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, + # while adding convenience for endpoint construction. + request = HttpRequest(method="GET", url=f"/indexes('{index_name}')?api-version=2024-05-01-preview") + async with client: + response = await client.send_request(request) + response.raise_for_status() + response_body = response.json() + print(response_body) + + +if __name__ == "__main__": + asyncio.run(sample_send_request()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py new file mode 100644 index 000000000000..8431867adfb0 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_index_crud_operations_async.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete an index. +USAGE: + python sample_index_crud_operations_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + + +import os +import asyncio +from typing import List + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.aio import SearchIndexClient +from azure.search.documents.indexes.models import ( + ComplexField, + CorsOptions, + SearchIndex, + ScoringProfile, + SearchFieldDataType, + SimpleField, + SearchableField, +) + + +async def create_index(): + # [START create_index_async] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profiles: List[ScoringProfile] = [] + index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) + + result = await client.create_index(index) + await client.close() + # [END create_index_async] + + +async def get_index(): + # [START get_index_async] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + result = await client.get_index(name) + await client.close() + # [END get_index_async] + + +async def update_index(): + # [START update_index_async] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + SimpleField(name="state", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) + + result = await client.create_or_update_index(index=index) + await client.close() + # [END update_index_async] + + +async def delete_index(): + # [START delete_index_async] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + await client.delete_index(name) + await client.close() + # [END delete_index_async] + + +async def main(): + await create_index() + await get_index() + await update_index() + await delete_index() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py new file mode 100644 index 000000000000..e83e1bbc66c3 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_indexers_operations_async.py @@ -0,0 +1,132 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_indexer_operations_async.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete a Indexer. +USAGE: + python sample_indexer_operations_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + +import asyncio +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] +connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.models import ( + SearchIndexerDataContainer, + SearchIndexerDataSourceConnection, + SearchIndex, + SearchIndexer, + SimpleField, + SearchFieldDataType, +) +from azure.search.documents.indexes.aio import SearchIndexerClient, SearchIndexClient + +indexers_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + + +async def create_indexer(): + # create an index + index_name = "async-indexer-hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + index = SearchIndex(name=index_name, fields=fields) + ind_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + async with ind_client: + await ind_client.create_index(index) + + # [START create_indexer_async] + # create a datasource + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name="async-indexer-datasource", type="azureblob", connection_string=connection_string, container=container + ) + data_source = await indexers_client.create_data_source_connection(data_source_connection) + + # create an indexer + indexer = SearchIndexer( + name="async-sample-indexer", + data_source_name="async-indexer-datasource", + target_index_name="async-indexer-hotels", + ) + result = await indexers_client.create_indexer(indexer) + print("Create new Indexer - async-sample-indexer") + # [END create_indexer_async] + + +async def list_indexers(): + # [START list_indexer_async] + result = await indexers_client.get_indexers() + names = [x.name for x in result] + print("Found {} Indexers in the service: {}".format(len(result), ", ".join(names))) + # [END list_indexer_async] + + +async def get_indexer(): + # [START get_indexer_async] + result = await indexers_client.get_indexer("async-sample-indexer") + print("Retrived Indexer 'async-sample-indexer'") + return result + # [END get_indexer_async] + + +async def get_indexer_status(): + # [START get_indexer_status_async] + result = await indexers_client.get_indexer_status("async-sample-indexer") + print("Retrived Indexer status for 'async-sample-indexer'") + return result + # [END get_indexer_status_async] + + +async def run_indexer(): + # [START run_indexer_async] + await indexers_client.run_indexer("async-sample-indexer") + print("Ran the Indexer 'async-sample-indexer'") + return + # [END run_indexer_async] + + +async def reset_indexer(): + # [START reset_indexer_async] + await indexers_client.reset_indexer("async-sample-indexer") + print("Reset the Indexer 'async-sample-indexer'") + return + # [END reset_indexer_async] + + +async def delete_indexer(): + # [START delete_indexer_async] + await indexers_client.delete_indexer("async-sample-indexer") + print("Indexer 'async-sample-indexer' successfully deleted") + # [END delete_indexer_async] + + +async def main(): + await create_indexer() + await list_indexers() + await get_indexer() + await get_indexer_status() + await run_indexer() + await reset_indexer() + await delete_indexer() + await indexers_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py new file mode 100644 index 000000000000..bfd02c0b6e27 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_query_session_async.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_query_session_async.py +DESCRIPTION: + To ensure more consistent and unique search results within a user's session, you can use session id. + Simply include the session_id parameter in your queries to create a unique identifier for each user session. + This ensures a uniform experience for users throughout their "query session". +USAGE: + python sample_query_session_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def query_session(): + # [START query_session_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + results = await search_client.search(search_text="spa", session_id="session-1") + + print("Hotels containing 'spa' in the name (or other fields):") + async for result in results: + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) + # [END query_session_async] + + +if __name__ == "__main__": + asyncio.run(query_session()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py new file mode 100644 index 000000000000..3a9c0c13d185 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_search_client_send_request_async.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_search_client_send_request_async.py + +DESCRIPTION: + This sample demonstrates how to make custom HTTP requests through a client pipeline. + +USAGE: + python sample_search_client_send_request_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import asyncio +import os +from azure.core.credentials import AzureKeyCredential +from azure.core.rest import HttpRequest +from azure.search.documents.aio import SearchClient + + +async def sample_send_request(): + endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + client = SearchClient(endpoint, index_name, AzureKeyCredential(key)) + + # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, + # while adding convenience for endpoint construction. + request = HttpRequest(method="GET", url=f"/docs/$count?api-version=2024-05-01-preview") + async with client: + response = await client.send_request(request) + response.raise_for_status() + response_body = response.json() + print(response_body) + + +if __name__ == "__main__": + asyncio.run(sample_send_request()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py new file mode 100644 index 000000000000..42a0cb2874ee --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_semantic_search_async.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_semantic_search_async.py +DESCRIPTION: + This sample demonstrates how to use semantic search. +USAGE: + python sample_semantic_search_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + + +async def speller(): + # [START speller_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + credential = AzureKeyCredential(key) + client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) + results = await client.search(search_text="luxury", query_language="en-us", query_speller="lexicon") + + async for result in results: + print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) + # [END speller_async] + + +async def semantic_ranking(): + # [START semantic_ranking_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + credential = AzureKeyCredential(key) + client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) + results = list( + client.search( + search_text="luxury", + query_type="semantic", + semantic_configuration_name="semantic_config_name", + query_language="en-us", + ) + ) + + for result in results: + print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) + # [END semantic_ranking_async] + + +if __name__ == "__main__": + asyncio.run(speller()) + asyncio.run(semantic_ranking()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py new file mode 100644 index 000000000000..d5f62acb4ff6 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_simple_query_async.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_simple_query_async.py +DESCRIPTION: + This sample demonstrates how to get search results from a basic search text + from an Azure Search index. +USAGE: + python sample_simple_query_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def simple_text_query(): + # [START simple_query_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + results = await search_client.search(search_text="spa") + + print("Hotels containing 'spa' in the name (or other fields):") + async for result in results: + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) + # [END simple_query_async] + + +if __name__ == "__main__": + asyncio.run(simple_text_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py new file mode 100644 index 000000000000..8f3fef5a90af --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_suggestions_async.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_suggestions_async.py +DESCRIPTION: + This sample demonstrates how to obtain search suggestions from an Azure + search index. +USAGE: + python sample_suggestions_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +async def suggest_query(): + # [START suggest_query_async] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.aio import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + async with search_client: + results = await search_client.suggest(search_text="coffee", suggester_name="sg") + + print("Search suggestions for 'coffee'") + for result in results: + hotel = await search_client.get_document(key=result["hotelId"]) + print(" Text: {} for Hotel: {}".format(repr(result["text"]), hotel["hotelName"])) + # [END suggest_query_async] + + +if __name__ == "__main__": + asyncio.run(suggest_query()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py new file mode 100644 index 000000000000..d45d375563d9 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_synonym_map_operations_async.py @@ -0,0 +1,80 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_synonym_map_operations_async.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete a Synonym Map. +USAGE: + python sample_synonym_map_operations_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + +import asyncio +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.aio import SearchIndexClient +from azure.search.documents.indexes.models import SynonymMap + +client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + +async def create_synonym_map(): + # [START create_synonym_map_async] + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name="test-syn-map", synonyms=synonyms) + result = await client.create_synonym_map(synonym_map) + print("Create new Synonym Map 'test-syn-map succeeded") + # [END create_synonym_map_async] + + +async def get_synonym_maps(): + # [START get_synonym_maps_async] + result = await client.get_synonym_maps() + names = [x.name for x in result] + print("Found {} Synonym Maps in the service: {}".format(len(result), ", ".join(names))) + # [END get_synonym_maps_async] + + +async def get_synonym_map(): + # [START get_synonym_map_async] + result = await client.get_synonym_map("test-syn-map") + print("Retrived Synonym Map 'test-syn-map' with synonyms") + if result: + for syn in result.synonyms: + print(" {}".format(syn)) + # [END get_synonym_map_async] + + +async def delete_synonym_map(): + # [START delete_synonym_map_async] + await client.delete_synonym_map("test-syn-map") + print("Synonym Map 'test-syn-map' deleted") + # [END delete_synonym_map_async] + + +async def main(): + await create_synonym_map() + await get_synonym_maps() + await get_synonym_map() + await delete_synonym_map() + await client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py b/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py new file mode 100644 index 000000000000..269226f313d6 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/async_samples/sample_vector_search_async.py @@ -0,0 +1,203 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_vector_search_async.py +DESCRIPTION: + This sample demonstrates how to get search results from a basic search text + from an Azure Search index. +USAGE: + python sample_vector_search_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +import asyncio + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.aio import SearchClient +from azure.search.documents.indexes import SearchIndexClient +from azure.search.documents.models import VectorizedQuery + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def get_embeddings(text: str): + # There are a few ways to get embeddings. This is just one example. + import openai + + open_ai_endpoint = os.getenv("OpenAIEndpoint") + open_ai_key = os.getenv("OpenAIKey") + + client = openai.AzureOpenAI( + azure_endpoint=open_ai_endpoint, + api_key=open_ai_key, + api_version="2023-09-01-preview", + ) + embedding = client.embeddings.create(input=[text], model="text-embedding-ada-002") + return embedding.data[0].embedding + + +def get_hotel_index(name: str): + from azure.search.documents.indexes.models import ( + SearchIndex, + SearchField, + SearchFieldDataType, + SimpleField, + SearchableField, + VectorSearch, + VectorSearchProfile, + HnswAlgorithmConfiguration, + ) + + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SearchableField(name="hotelName", type=SearchFieldDataType.String, sortable=True, filterable=True), + SearchableField(name="description", type=SearchFieldDataType.String), + SearchField( + name="descriptionVector", + type=SearchFieldDataType.Collection(SearchFieldDataType.Single), + searchable=True, + vector_search_dimensions=1536, + vector_search_profile_name="my-vector-config", + ), + SearchableField( + name="category", type=SearchFieldDataType.String, sortable=True, filterable=True, facetable=True + ), + ] + vector_search = VectorSearch( + profiles=[VectorSearchProfile(name="my-vector-config", algorithm_configuration_name="my-algorithms-config")], + algorithms=[HnswAlgorithmConfiguration(name="my-algorithms-config")], + ) + return SearchIndex(name=name, fields=fields, vector_search=vector_search) + + +def get_hotel_documents(): + docs = [ + { + "hotelId": "1", + "hotelName": "Fancy Stay", + "description": "Best hotel in town if you like luxury hotels.", + "descriptionVector": get_embeddings("Best hotel in town if you like luxury hotels."), + "category": "Luxury", + }, + { + "hotelId": "2", + "hotelName": "Roach Motel", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionVector": get_embeddings("Cheapest hotel in town. Infact, a motel."), + "category": "Budget", + }, + { + "hotelId": "3", + "hotelName": "EconoStay", + "description": "Very popular hotel in town.", + "descriptionVector": get_embeddings("Very popular hotel in town."), + "category": "Budget", + }, + { + "hotelId": "4", + "hotelName": "Modern Stay", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionVector": get_embeddings( + "Modern architecture, very polite staff and very clean. Also very affordable." + ), + "category": "Luxury", + }, + { + "hotelId": "5", + "hotelName": "Secret Point", + "description": "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York.", + "descriptionVector": get_embeddings( + "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York." + ), + "category": "Boutique", + }, + ] + return docs + + +async def single_vector_search(): + # [START single_vector_search] + query = "Top hotels in town" + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") + + async with search_client: + results = await search_client.search( + search_text="", + vector_queries=[vector_query], + select=["hotelId", "hotelName"], + ) + + async for result in results: + print(result) + # [END single_vector_search] + + +async def single_vector_search_with_filter(): + # [START single_vector_search_with_filter] + query = "Top hotels in town" + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") + + async with search_client: + results = await search_client.search( + vector_queries=[vector_query], + filter="category eq 'Luxury'", + select=["hotelId", "hotelName"], + ) + + async for result in results: + print(result) + # [END single_vector_search_with_filter] + + +async def simple_hybrid_search(): + # [START simple_hybrid_search] + query = "Top hotels in town" + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") + + async with search_client: + results = await search_client.search( + search_text=query, + vector_queries=[vector_query], + select=["hotelId", "hotelName"], + ) + + async for result in results: + print(result) + # [END simple_hybrid_search] + + +async def main(): + credential = AzureKeyCredential(key) + index_client = SearchIndexClient(service_endpoint, credential) + index = get_hotel_index(index_name) + index_client.create_index(index) + client = SearchClient(service_endpoint, index_name, credential) + hotel_docs = get_hotel_documents() + await client.upload_documents(documents=hotel_docs) + + await single_vector_search() + await single_vector_search_with_filter() + await simple_hybrid_search() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/search/azure-search-documents/samples/batch_upload.py b/sdk/search/azure-search-documents/samples/batch_upload.py new file mode 100644 index 000000000000..da4f83564959 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/batch_upload.py @@ -0,0 +1,10 @@ +from azure.search.documents import SearchClient +from azure.identity import AzureCliCredential + +client = SearchClient( + endpoint="https://vector-search-test.search.windows.net", + index_name="batch-test", + credential=AzureCliCredential(), +) +documents = [{"id": str(i), "content": " " * 10000} for i in range(10000)] +client.upload_documents(documents=documents) diff --git a/sdk/search/azure-search-documents/samples/files/hotel_small.json b/sdk/search/azure-search-documents/samples/files/hotel_small.json new file mode 100644 index 000000000000..e30a1f96199b --- /dev/null +++ b/sdk/search/azure-search-documents/samples/files/hotel_small.json @@ -0,0 +1,252 @@ +[ + { + "@search.action": "upload", + "hotelId": "1", + "hotelName": "Fancy Stay", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "2", + "hotelName": "Roach Motel", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "3", + "hotelName": "EconoStay", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "4", + "hotelName": "Express Rooms", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "5", + "hotelName": "Comfy Place", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "6", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "7", + "hotelName": "Modern Stay", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "8", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "9", + "hotelName": "Secret Point Motel", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "10", + "hotelName": "Countryside Hotel", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + } +] diff --git a/sdk/search/azure-search-documents/samples/sample_analyze_text.py b/sdk/search/azure-search-documents/samples/sample_analyze_text.py new file mode 100644 index 000000000000..3a239870ea17 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_analyze_text.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_analyze_text.py +DESCRIPTION: + This sample demonstrates how to analyze text. +USAGE: + python sample_analyze_text.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def simple_analyze_text(): + # [START simple_analyze_text] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.indexes import SearchIndexClient + from azure.search.documents.indexes.models import AnalyzeTextOptions + + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") + + result = client.analyze_text(index_name, analyze_request) + print(result.as_dict()) + # [END simple_analyze_text] + + +if __name__ == "__main__": + simple_analyze_text() diff --git a/sdk/search/azure-search-documents/samples/sample_authentication.py b/sdk/search/azure-search-documents/samples/sample_authentication.py new file mode 100644 index 000000000000..f690c7ff7e17 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_authentication.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_authentication.py +DESCRIPTION: + This sample demonstrates how to authenticate with the Azure Congnitive Search + service with an API key. See more details about authentication here: + https://learn.microsoft.com/azure.search.documents/search-security-api-keys +USAGE: + python sample_authentication.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + + +def authentication_with_api_key_credential(): + # [START create_search_client_with_key] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + # [END create_search_client_with_key] + + result = search_client.get_document_count() + + print("There are {} documents in the {} search index.".format(result, index_name)) + + +def authentication_service_client_with_api_key_credential(): + # [START create_search_service_client_with_key] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents.indexes import SearchIndexClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + search_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + # [END create_search_service_client_with_key] + + +def authentication_with_aad(): + # [START authentication_with_aad] + from azure.identity import DefaultAzureCredential + from azure.search.documents import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + credential = DefaultAzureCredential() + + search_client = SearchClient(service_endpoint, index_name, credential) + # [END authentication_with_aad] + + result = search_client.get_document_count() + + print("There are {} documents in the {} search index.".format(result, index_name)) + + +def authentication_service_client_with_aad(): + # [START authentication_service_client_with_aad] + from azure.identity import DefaultAzureCredential + from azure.search.documents.indexes import SearchIndexClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + credential = DefaultAzureCredential() + + search_client = SearchIndexClient(service_endpoint, credential) + # [END authentication_service_client_with_aad] + + +if __name__ == "__main__": + authentication_with_api_key_credential() + authentication_service_client_with_api_key_credential() + authentication_with_aad() + authentication_service_client_with_aad() diff --git a/sdk/search/azure-search-documents/samples/sample_autocomplete.py b/sdk/search/azure-search-documents/samples/sample_autocomplete.py new file mode 100644 index 000000000000..7846637b5dbc --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_autocomplete.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_autocomplete.py +DESCRIPTION: + This sample demonstrates how to obtain autocompletion suggestions from an + Azure Search index. +USAGE: + python sample_autocomplete.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def autocomplete_query(): + # [START autocomplete_query] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + results = search_client.autocomplete(search_text="bo", suggester_name="sg") + + print("Autocomplete suggestions for 'bo'") + for result in results: + print(" Completion: {}".format(result["text"])) + # [END autocomplete_query] + + +if __name__ == "__main__": + autocomplete_query() diff --git a/sdk/search/azure-search-documents/samples/sample_buffered_sender.py b/sdk/search/azure-search-documents/samples/sample_buffered_sender.py new file mode 100644 index 000000000000..db7de92154a2 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_buffered_sender.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_batch_client.py +DESCRIPTION: + This sample demonstrates how to upload, merge, or delete documents using SearchIndexingBufferedSender. +USAGE: + python sample_batch_client.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchIndexingBufferedSender + + +def sample_batching_client(): + DOCUMENT = { + "category": "Hotel", + "hotelId": "1000", + "rating": 4.0, + "rooms": [], + "hotelName": "Azure Inn", + } + + with SearchIndexingBufferedSender(service_endpoint, index_name, AzureKeyCredential(key)) as batch_client: + # add upload actions + batch_client.upload_documents(documents=[DOCUMENT]) + # add merge actions + batch_client.merge_documents(documents=[{"hotelId": "1000", "rating": 4.5}]) + # add delete actions + batch_client.delete_documents(documents=[{"hotelId": "1000"}]) + + +if __name__ == "__main__": + sample_batching_client() diff --git a/sdk/search/azure-search-documents/samples/sample_crud_operations.py b/sdk/search/azure-search-documents/samples/sample_crud_operations.py new file mode 100644 index 000000000000..de22c6b5cb82 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_crud_operations.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_crud_operations.py +DESCRIPTION: + This sample demonstrates how to upload, merge, or delete documents from an + Azure Search index. +USAGE: + python sample_crud_operations.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchClient + +search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + +def upload_document(): + # [START upload_document] + DOCUMENT = { + "hotelId": "1000", + "hotelName": "Azure Inn", + } + + result = search_client.upload_documents(documents=[DOCUMENT]) + + print("Upload of new document succeeded: {}".format(result[0].succeeded)) + # [END upload_document] + + +def merge_document(): + # [START merge_document] + result = search_client.merge_documents(documents=[{"hotelId": "783", "hotelName": "Renovated Ranch"}]) + + print("Merge into new document succeeded: {}".format(result[0].succeeded)) + # [END merge_document] + + +def delete_document(): + # [START delete_document] + result = search_client.delete_documents(documents=[{"hotelId": "1000"}]) + + print("Delete new document succeeded: {}".format(result[0].succeeded)) + # [END delete_document] + + +if __name__ == "__main__": + upload_document() + merge_document() + delete_document() diff --git a/sdk/search/azure-search-documents/samples/sample_data_source_operations.py b/sdk/search/azure-search-documents/samples/sample_data_source_operations.py new file mode 100644 index 000000000000..cf14b3fa25cf --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_data_source_operations.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_data_source_operations.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete a Data Source. +USAGE: + python sample_data_source_operations.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] +connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes import SearchIndexerClient +from azure.search.documents.indexes.models import SearchIndexerDataContainer, SearchIndexerDataSourceConnection + +client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + + +def create_data_source_connection(): + # [START create_data_source_connection] + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name="sample-data-source-connection", type="azureblob", connection_string=connection_string, container=container + ) + result = client.create_data_source_connection(data_source_connection) + print(result) + print("Create new Data Source Connection - sample-data-source-connection") + # [END create_data_source_connection] + + +def list_data_source_connections(): + # [START list_data_source_connection] + result = client.get_data_source_connections() + names = [ds.name for ds in result] + print("Found {} Data Source Connections in the service: {}".format(len(result), ", ".join(names))) + # [END list_data_source_connection] + + +def get_data_source_connection(): + # [START get_data_source_connection] + result = client.get_data_source_connection("sample-data-source-connection") + print("Retrived Data Source Connection 'sample-data-source-connection'") + # [END get_data_source_connection] + + +def delete_data_source_connection(): + # [START delete_data_source_connection] + client.delete_data_source_connection("sample-data-source-connection") + print("Data Source Connection 'sample-data-source-connection' successfully deleted") + # [END delete_data_source_connection] + + +if __name__ == "__main__": + create_data_source_connection() + list_data_source_connections() + get_data_source_connection() + delete_data_source_connection() diff --git a/sdk/search/azure-search-documents/samples/sample_facet_query.py b/sdk/search/azure-search-documents/samples/sample_facet_query.py new file mode 100644 index 000000000000..a70078173d11 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_facet_query.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_facet_query.py +DESCRIPTION: + This sample demonstrates how to obtain search facets on specified field in + an Azure Search index. +USAGE: + python sample_facet_query.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +from typing import List, Dict, cast +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def filter_query(): + # [START facet_query] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + results = search_client.search(search_text="WiFi", facets=["category,count:3", "parkingIncluded"]) + + facets: Dict[str, List[str]] = cast(Dict[str, List[str]], results.get_facets()) + + print("Catgory facet counts for hotels:") + for facet in facets["category"]: + print(" {}".format(facet)) + # [END facet_query] + + +if __name__ == "__main__": + filter_query() diff --git a/sdk/search/azure-search-documents/samples/sample_filter_query.py b/sdk/search/azure-search-documents/samples/sample_filter_query.py new file mode 100644 index 000000000000..432edf9a1f02 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_filter_query.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_filter_query.py +DESCRIPTION: + This sample demonstrates how search results from an Azure Search index can + be filtered and ordered. +USAGE: + python sample_filter_query.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def filter_query(): + # [START filter_query] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + results = search_client.search( + search_text="WiFi", + filter="Address/StateProvince eq 'FL' and Address/Country eq 'USA'", + select=["hotelName", "rating"], + order_by=["rating desc"], + ) + + print("Florida hotels containing 'WiFi', sorted by Rating:") + for result in results: + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) + # [END filter_query] + + +if __name__ == "__main__": + filter_query() diff --git a/sdk/search/azure-search-documents/samples/sample_get_document.py b/sdk/search/azure-search-documents/samples/sample_get_document.py new file mode 100644 index 000000000000..0a5addfa14cb --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_get_document.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_document.py +DESCRIPTION: + This sample demonstrates how to retrieve a specific document by key from an + Azure Search index. +USAGE: + python sample_get_document.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def get_document(): + # [START get_document] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + result = search_client.get_document(key="23") + + print("Details for hotel '23' are:") + print(" Name: {}".format(result["hotelName"])) + # [END get_document] + + +if __name__ == "__main__": + get_document() diff --git a/sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py b/sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py new file mode 100644 index 000000000000..52220f12b8e4 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_index_alias_crud_operations.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_index_alias_crud_operations.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete an alias with an existing index. +USAGE: + python sample_index_alias_crud_operations.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key + 3) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") +""" + + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] +alias_name = "motels" + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes import SearchIndexClient +from azure.search.documents.indexes.models import ( + ComplexField, + CorsOptions, + ScoringProfile, + SearchAlias, + SearchIndex, + SimpleField, + SearchableField, + SearchFieldDataType, +) + + +client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + +def create_alias(): + # [START create_alias] + alias = SearchAlias(name=alias_name, indexes=[index_name]) + result = client.create_alias(alias) + # [END create_alias] + + +def get_alias(): + # [START get_alias] + result = client.get_alias(alias_name) + # [END get_alias] + + +def update_alias(): + # [START update_alias] + new_index_name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + SearchableField(name="hotelName", type=SearchFieldDataType.String), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + SimpleField(name="state", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex( + name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options + ) + + result_index = client.create_or_update_index(index=index) + + alias = SearchAlias(name=alias_name, indexes=[new_index_name]) + result = client.create_or_update_alias(alias) + + # [END update_alias] + + +def delete_alias(): + # [START delete_alias] + + client.delete_alias(alias_name) + # [END delete_alias] + + +if __name__ == "__main__": + create_alias() + get_alias() + update_alias() + delete_alias() diff --git a/sdk/search/azure-search-documents/samples/sample_index_client_send_request.py b/sdk/search/azure-search-documents/samples/sample_index_client_send_request.py new file mode 100644 index 000000000000..f8b373b1970b --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_index_client_send_request.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_index_client_send_request.py + +DESCRIPTION: + This sample demonstrates how to make custom HTTP requests through a client pipeline. + +USAGE: + python sample_index_client_send_request.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +from azure.core.credentials import AzureKeyCredential +from azure.core.rest import HttpRequest +from azure.search.documents.indexes import SearchIndexClient + + +def sample_send_request(): + endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + client = SearchIndexClient(endpoint, AzureKeyCredential(key)) + + # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, + # while adding convenience for endpoint construction. + request = HttpRequest(method="GET", url=f"/indexes('{index_name}')?api-version=2024-05-01-preview") + response = client.send_request(request) + response.raise_for_status() + response_body = response.json() + print(response_body) + + +if __name__ == "__main__": + sample_send_request() diff --git a/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py b/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py new file mode 100644 index 000000000000..6b0cabb2c2dd --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_index_crud_operations.py @@ -0,0 +1,116 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_index_crud_operations.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete an index. +USAGE: + python sample_index_crud_operations.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + + +import os +from typing import List + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes import SearchIndexClient +from azure.search.documents.indexes.models import ( + ComplexField, + CorsOptions, + SearchIndex, + ScoringProfile, + SearchFieldDataType, + SimpleField, + SearchableField, +) + + +def create_index(): + # [START create_index] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profiles: List[ScoringProfile] = [] + index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) + + result = client.create_index(index) + # [END create_index] + + +def get_index(): + # [START get_index] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + result = client.get_index(name) + # [END get_index] + + +def update_index(): + # [START update_index] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelName", type=SearchFieldDataType.String, searchable=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + SimpleField(name="state", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) + + result = client.create_or_update_index(index=index) + # [END update_index] + + +def delete_index(): + # [START delete_index] + client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + name = "hotels" + client.delete_index(name) + # [END delete_index] + + +if __name__ == "__main__": + create_index() + get_index() + update_index() + delete_index() diff --git a/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py b/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py new file mode 100644 index 000000000000..b0654e56210f --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_indexer_datasource_skillset.py @@ -0,0 +1,152 @@ +""" +FILE: sample_indexer_datasource_skillset.py +DESCRIPTION: + This sample demonstrates use an indexer, datasource and skillset together. + + Indexer is used to efficiently write data to an index using a datasource. + So we first identify a supported data source - we use azure storage blobs + in this example. Then we create an index which is compatible with the datasource. + Further, we create an azure cognitive search datasource which we require to finally + create an indexer. + + Additionally, we will also use skillsets to provide some AI enhancements in our indexers. + + Once we create the indexer, we run the indexer and perform some basic operations like getting + the indexer status. + + The datasource used in this sample is stored as metadata for empty blobs in "searchcontainer". + The json file can be found in samples/files folder named hotel_small.json has the metdata of + each blob. +USAGE: + python sample_indexer_datasource_skillset.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key + 3) AZURE_STORAGE_CONNECTION_STRING - The connection string for the storage blob account that is + being used to create the datasource. +""" + +import os +import datetime + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] +connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.models import ( + SearchIndexerDataContainer, + SearchIndex, + SearchIndexer, + SimpleField, + SearchFieldDataType, + EntityRecognitionSkill, + InputFieldMappingEntry, + OutputFieldMappingEntry, + SearchIndexerSkillset, + CorsOptions, + IndexingSchedule, + SearchableField, + IndexingParameters, + SearchIndexerDataSourceConnection, + IndexingParametersConfiguration, +) +from azure.search.documents.indexes import SearchIndexerClient, SearchIndexClient + + +def _create_index(): + name = "hotel-index" + + # Here we create an index with listed fields. + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, filterable=True, sortable=True, key=True), + SearchableField(name="hotelName", type=SearchFieldDataType.String), + SimpleField(name="description", type=SearchFieldDataType.String), + SimpleField(name="descriptionFr", type=SearchFieldDataType.String), + SimpleField(name="category", type=SearchFieldDataType.String), + SimpleField(name="parkingIncluded", type=SearchFieldDataType.Boolean, filterable=True), + SimpleField(name="smokingAllowed", type=SearchFieldDataType.Boolean, filterable=True), + SimpleField(name="lastRenovationDate", type=SearchFieldDataType.String), + SimpleField(name="rating", type=SearchFieldDataType.Int64, sortable=True), + SimpleField(name="location", type=SearchFieldDataType.GeographyPoint), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + + # pass in the name, fields and cors options and create the index + index = SearchIndex(name=name, fields=fields, cors_options=cors_options) + index_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + result = index_client.create_index(index) + return result + + +def _create_datasource(): + # Here we create a datasource. As mentioned in the description we have stored it in + # "searchcontainer" + ds_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name="hotel-datasource", type="azureblob", connection_string=connection_string, container=container + ) + data_source = ds_client.create_data_source_connection(data_source_connection) + return data_source + + +def _create_skillset(): + client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + inp = InputFieldMappingEntry(name="text", source="/document/lastRenovationDate") + output = OutputFieldMappingEntry(name="dateTimes", target_name="RenovatedDate") + s = EntityRecognitionSkill(name="merge-skill", inputs=[inp], outputs=[output]) + + skillset = SearchIndexerSkillset(name="hotel-data-skill", skills=[s], description="example skillset") + result = client.create_skillset(skillset) + return result + + +def sample_indexer_workflow(): + # Now that we have a datasource and an index, we can create an indexer. + + skillset_name = _create_skillset().name + print("Skillset is created") + + ds_name = _create_datasource().name + print("Data source is created") + + ind_name = _create_index().name + print("Index is created") + + # we pass the data source, skillsets and targeted index to build an indexer + configuration = IndexingParametersConfiguration(parsing_mode="jsonArray", query_timeout=None) # type: ignore + parameters = IndexingParameters(configuration=configuration) + indexer = SearchIndexer( + name="hotel-data-indexer", + data_source_name=ds_name, + target_index_name=ind_name, + skillset_name=skillset_name, + parameters=parameters, + ) + + indexer_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + indexer_client.create_indexer(indexer) # create the indexer + + # to get an indexer + result = indexer_client.get_indexer("hotel-data-indexer") + print(result) + + # To run an indexer, we can use run_indexer() + indexer_client.run_indexer(result.name) + + # Using create or update to schedule an indexer + + schedule = IndexingSchedule(interval=datetime.timedelta(hours=24)) + result.schedule = schedule + updated_indexer = indexer_client.create_or_update_indexer(result) + + print(updated_indexer) + + # get the status of an indexer + indexer_client.get_indexer_status(updated_indexer.name) + + +if __name__ == "__main__": + sample_indexer_workflow() diff --git a/sdk/search/azure-search-documents/samples/sample_indexers_operations.py b/sdk/search/azure-search-documents/samples/sample_indexers_operations.py new file mode 100644 index 000000000000..ff854d51be96 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_indexers_operations.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_indexer_operations.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete a Indexer. +USAGE: + python sample_indexer_operations.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] +connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes.models import ( + SearchIndexerDataContainer, + SearchIndexerDataSourceConnection, + SearchIndex, + SearchIndexer, + SimpleField, + SearchFieldDataType, +) +from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient + +indexers_client = SearchIndexerClient(service_endpoint, AzureKeyCredential(key)) + + +def create_indexer(): + # create an index + index_name = "indexer-hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + index = SearchIndex(name=index_name, fields=fields) + ind_client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + ind_client.create_index(index) + + # [START create_indexer] + # create a datasource + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name="indexer-datasource", type="azureblob", connection_string=connection_string, container=container + ) + data_source = indexers_client.create_data_source_connection(data_source_connection) + + # create an indexer + indexer = SearchIndexer( + name="sample-indexer", data_source_name="indexer-datasource", target_index_name="indexer-hotels" + ) + result = indexers_client.create_indexer(indexer) + print("Create new Indexer - sample-indexer") + # [END create_indexer] + + +def list_indexers(): + # [START list_indexer] + result = indexers_client.get_indexers() + names = [x.name for x in result] + print("Found {} Indexers in the service: {}".format(len(result), ", ".join(names))) + # [END list_indexer] + + +def get_indexer(): + # [START get_indexer] + result = indexers_client.get_indexer("sample-indexer") + print("Retrived Indexer 'sample-indexer'") + return result + # [END get_indexer] + + +def get_indexer_status(): + # [START get_indexer_status] + result = indexers_client.get_indexer_status("sample-indexer") + print("Retrived Indexer status for 'sample-indexer'") + return result + # [END get_indexer_status] + + +def run_indexer(): + # [START run_indexer] + result = indexers_client.run_indexer("sample-indexer") + print("Ran the Indexer 'sample-indexer'") + return result + # [END run_indexer] + + +def reset_indexer(): + # [START reset_indexer] + result = indexers_client.reset_indexer("sample-indexer") + print("Reset the Indexer 'sample-indexer'") + return result + # [END reset_indexer] + + +def delete_indexer(): + # [START delete_indexer] + indexers_client.delete_indexer("sample-indexer") + print("Indexer 'sample-indexer' successfully deleted") + # [END delete_indexer] + + +if __name__ == "__main__": + create_indexer() + list_indexers() + get_indexer() + get_indexer_status() + run_indexer() + reset_indexer() + delete_indexer() diff --git a/sdk/search/azure-search-documents/samples/sample_query_session.py b/sdk/search/azure-search-documents/samples/sample_query_session.py new file mode 100644 index 000000000000..64e783ff636a --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_query_session.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_query_session.py +DESCRIPTION: + To ensure more consistent and unique search results within a user's session, you can use session id. + Simply include the session_id parameter in your queries to create a unique identifier for each user session. + This ensures a uniform experience for users throughout their "query session". +USAGE: + python sample_query_session.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def query_session(): + # [START query_session] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + results = search_client.search(search_text="spa", session_id="session-1") + + print("Hotels containing 'spa' in the name (or other fields):") + for result in results: + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) + # [END query_session] + + +if __name__ == "__main__": + query_session() diff --git a/sdk/search/azure-search-documents/samples/sample_search_client_send_request.py b/sdk/search/azure-search-documents/samples/sample_search_client_send_request.py new file mode 100644 index 000000000000..616d04fe0e52 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_search_client_send_request.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_search_client_send_request.py + +DESCRIPTION: + This sample demonstrates how to make custom HTTP requests through a client pipeline. + +USAGE: + python sample_search_client_send_request.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os +from azure.core.credentials import AzureKeyCredential +from azure.core.rest import HttpRequest +from azure.search.documents import SearchClient + + +def sample_send_request(): + endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + client = SearchClient(endpoint, index_name, AzureKeyCredential(key)) + + # The `send_request` method can send custom HTTP requests that share the client's existing pipeline, + # while adding convenience for endpoint construction. + request = HttpRequest(method="GET", url=f"/docs/$count?api-version=2024-05-01-preview") + response = client.send_request(request) + response.raise_for_status() + response_body = response.json() + print(response_body) + + +if __name__ == "__main__": + sample_send_request() diff --git a/sdk/search/azure-search-documents/samples/sample_semantic_search.py b/sdk/search/azure-search-documents/samples/sample_semantic_search.py new file mode 100644 index 000000000000..c6e5be9c57ad --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_semantic_search.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_semantic_search.py +DESCRIPTION: + This sample demonstrates how to use semantic search. +USAGE: + python sample_semantic_search.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + + +def speller(): + # [START speller] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + credential = AzureKeyCredential(key) + client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) + results = list(client.search(search_text="luxury", query_language="en-us", query_speller="lexicon")) + + for result in results: + print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) + # [END speller] + + +def semantic_ranking(): + # [START semantic_ranking] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] + index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] + key = os.environ["AZURE_SEARCH_API_KEY"] + + credential = AzureKeyCredential(key) + client = SearchClient(endpoint=service_endpoint, index_name=index_name, credential=credential) + results = list( + client.search( + search_text="luxury", + query_type="semantic", + semantic_configuration_name="semantic_config_name", + query_language="en-us", + ) + ) + + for result in results: + print("{}\n{}\n)".format(result["hotelId"], result["hotelName"])) + # [END semantic_ranking] + + +if __name__ == "__main__": + speller() + semantic_ranking() diff --git a/sdk/search/azure-search-documents/samples/sample_simple_query.py b/sdk/search/azure-search-documents/samples/sample_simple_query.py new file mode 100644 index 000000000000..9f2317a008e3 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_simple_query.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_simple_query.py +DESCRIPTION: + This sample demonstrates how to get search results from a basic search text + from an Azure Search index. +USAGE: + python sample_simple_query.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def simple_text_query(): + # [START simple_query] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + results = search_client.search(search_text="spa") + + print("Hotels containing 'spa' in the name (or other fields):") + for result in results: + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) + # [END simple_query] + + +if __name__ == "__main__": + simple_text_query() diff --git a/sdk/search/azure-search-documents/samples/sample_suggestions.py b/sdk/search/azure-search-documents/samples/sample_suggestions.py new file mode 100644 index 000000000000..e24478418b25 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_suggestions.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_suggestions.py +DESCRIPTION: + This sample demonstrates how to obtain search suggestions from an Azure + search index +USAGE: + python sample_suggestions.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def suggest_query(): + # [START suggest_query] + from azure.core.credentials import AzureKeyCredential + from azure.search.documents import SearchClient + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + + results = search_client.suggest(search_text="coffee", suggester_name="sg") + + print("Search suggestions for 'coffee'") + for result in results: + hotel = search_client.get_document(key=result["hotelId"]) + print(" Text: {} for Hotel: {}".format(repr(result["text"]), hotel["hotelName"])) + # [END suggest_query] + + +if __name__ == "__main__": + suggest_query() diff --git a/sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py b/sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py new file mode 100644 index 000000000000..c6f8b9575f40 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_synonym_map_operations.py +DESCRIPTION: + This sample demonstrates how to get, create, update, or delete a Synonym Map. +USAGE: + python sample_synonym_map_operations.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +key = os.environ["AZURE_SEARCH_API_KEY"] + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.indexes import SearchIndexClient +from azure.search.documents.indexes.models import SynonymMap + +client = SearchIndexClient(service_endpoint, AzureKeyCredential(key)) + + +def create_synonym_map(): + # [START create_synonym_map] + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name="test-syn-map", synonyms=synonyms) + result = client.create_synonym_map(synonym_map) + print("Create new Synonym Map 'test-syn-map succeeded") + # [END create_synonym_map] + + +def create_synonym_map_from_file(): + # [START create_synonym_map_from_file] + from os.path import dirname, join, realpath + + CWD = dirname(realpath(__file__)) + file_path = join(CWD, "synonym_map.txt") + with open(file_path, "r") as f: + solr_format_synonyms = f.read() + synonyms = solr_format_synonyms.split("\n") + synonym_map = SynonymMap(name="test-syn-map", synonyms=synonyms) + result = client.create_synonym_map(synonym_map) + print("Create new Synonym Map 'test-syn-map succeeded") + # [END create_synonym_map_from_file] + + +def get_synonym_maps(): + # [START get_synonym_maps] + result = client.get_synonym_maps() + names = [x.name for x in result] + print("Found {} Synonym Maps in the service: {}".format(len(result), ", ".join(names))) + # [END get_synonym_maps] + + +def get_synonym_map(): + # [START get_synonym_map] + result = client.get_synonym_map("test-syn-map") + print("Retrived Synonym Map 'test-syn-map' with synonyms") + if result: + for syn in result.synonyms: + print(" {}".format(syn)) + # [END get_synonym_map] + + +def delete_synonym_map(): + # [START delete_synonym_map] + client.delete_synonym_map("test-syn-map") + print("Synonym Map 'test-syn-map' deleted") + # [END delete_synonym_map] + + +if __name__ == "__main__": + create_synonym_map() + get_synonym_maps() + get_synonym_map() + delete_synonym_map() diff --git a/sdk/search/azure-search-documents/samples/sample_vector_search.py b/sdk/search/azure-search-documents/samples/sample_vector_search.py new file mode 100644 index 000000000000..b7bfbc31d44a --- /dev/null +++ b/sdk/search/azure-search-documents/samples/sample_vector_search.py @@ -0,0 +1,204 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_vector_search.py +DESCRIPTION: + This sample demonstrates how to get search results from a basic search text + from an Azure Search index. +USAGE: + python sample_vector_search.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchClient +from azure.search.documents.indexes import SearchIndexClient +from azure.search.documents.models import VectorizedQuery + +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] +key = os.environ["AZURE_SEARCH_API_KEY"] + + +def get_embeddings(text: str): + # There are a few ways to get embeddings. This is just one example. + import openai + + open_ai_endpoint = os.getenv("OpenAIEndpoint") + open_ai_key = os.getenv("OpenAIKey") + + client = openai.AzureOpenAI( + azure_endpoint=open_ai_endpoint, + api_key=open_ai_key, + api_version="2023-09-01-preview", + ) + embedding = client.embeddings.create(input=[text], model="text-embedding-ada-002") + return embedding.data[0].embedding + + +def get_hotel_index(name: str): + from azure.search.documents.indexes.models import ( + SearchIndex, + SearchField, + SearchFieldDataType, + SimpleField, + SearchableField, + VectorSearch, + VectorSearchProfile, + HnswAlgorithmConfiguration, + ) + + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SearchableField( + name="hotelName", + type=SearchFieldDataType.String, + sortable=True, + filterable=True, + ), + SearchableField(name="description", type=SearchFieldDataType.String), + SearchField( + name="descriptionVector", + type=SearchFieldDataType.Collection(SearchFieldDataType.Single), + searchable=True, + vector_search_dimensions=1536, + vector_search_profile_name="my-vector-config", + ), + SearchableField( + name="category", + type=SearchFieldDataType.String, + sortable=True, + filterable=True, + facetable=True, + ), + ] + vector_search = VectorSearch( + profiles=[VectorSearchProfile(name="my-vector-config", algorithm_configuration_name="my-algorithms-config")], + algorithms=[HnswAlgorithmConfiguration(name="my-algorithms-config")], + ) + return SearchIndex(name=name, fields=fields, vector_search=vector_search) + + +def get_hotel_documents(): + docs = [ + { + "hotelId": "1", + "hotelName": "Fancy Stay", + "description": "Best hotel in town if you like luxury hotels.", + "descriptionVector": get_embeddings("Best hotel in town if you like luxury hotels."), + "category": "Luxury", + }, + { + "hotelId": "2", + "hotelName": "Roach Motel", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionVector": get_embeddings("Cheapest hotel in town. Infact, a motel."), + "category": "Budget", + }, + { + "hotelId": "3", + "hotelName": "EconoStay", + "description": "Very popular hotel in town.", + "descriptionVector": get_embeddings("Very popular hotel in town."), + "category": "Budget", + }, + { + "hotelId": "4", + "hotelName": "Modern Stay", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionVector": get_embeddings( + "Modern architecture, very polite staff and very clean. Also very affordable." + ), + "category": "Luxury", + }, + { + "hotelId": "5", + "hotelName": "Secret Point", + "description": "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York.", + "descriptionVector": get_embeddings( + "One of the best hotel in town. The hotel is ideally located on the main commercial artery of the city in the heart of New York." + ), + "category": "Boutique", + }, + ] + return docs + + +def single_vector_search(): + # [START single_vector_search] + query = "Top hotels in town" + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") + + results = search_client.search( + vector_queries=[vector_query], + select=["hotelId", "hotelName"], + ) + + for result in results: + print(result) + # [END single_vector_search] + + +def single_vector_search_with_filter(): + # [START single_vector_search_with_filter] + query = "Top hotels in town" + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") + + results = search_client.search( + search_text="", + vector_queries=[vector_query], + filter="category eq 'Luxury'", + select=["hotelId", "hotelName"], + ) + + for result in results: + print(result) + # [END single_vector_search_with_filter] + + +def simple_hybrid_search(): + # [START simple_hybrid_search] + query = "Top hotels in town" + + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) + vector_query = VectorizedQuery(vector=get_embeddings(query), k_nearest_neighbors=3, fields="descriptionVector") + + results = search_client.search( + search_text=query, + vector_queries=[vector_query], + select=["hotelId", "hotelName"], + ) + + for result in results: + print(result) + # [END simple_hybrid_search] + + +if __name__ == "__main__": + credential = AzureKeyCredential(key) + index_client = SearchIndexClient(service_endpoint, credential) + index = get_hotel_index(index_name) + index_client.create_index(index) + client = SearchClient(service_endpoint, index_name, credential) + hotel_docs = get_hotel_documents() + client.upload_documents(documents=hotel_docs) + + single_vector_search() + single_vector_search_with_filter() + simple_hybrid_search() diff --git a/sdk/search/azure-search-documents/samples/simple_query.py b/sdk/search/azure-search-documents/samples/simple_query.py new file mode 100644 index 000000000000..3fce6b4ba2d0 --- /dev/null +++ b/sdk/search/azure-search-documents/samples/simple_query.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_simple_query.py +DESCRIPTION: + This sample demonstrates how to get search results from a basic search text + from an Azure Search index. +USAGE: + python sample_simple_query.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") + 3) AZURE_SEARCH_API_KEY - your search API key +""" + +import os + +service_endpoint = "https://gh-issue-test.search.windows.net" +index_name = "document-index3-python" + + +def simple_text_query(): + # [START simple_query] + from azure.identity import AzureCliCredential + from azure.search.documents import SearchClient + from azure.search.documents.indexes.models import ( + SemanticConfiguration, + SemanticPrioritizedFields, + SemanticField, + ) + + search_client = SearchClient(service_endpoint, index_name, AzureCliCredential()) + # semantic_config = SemanticConfiguration( + # name="semantic_config_name", + # prioritized_fields=[ + # SemanticPrioritizedFields( + # title_field=SemanticField(field_name="Title"), + # content_fields=[ + # SemanticField(field_name="content") + # ] + # ) + # ] + # ) + + results = search_client.search( + search_text="luxury", + query_type="semantic", + debug="all", + semantic_configuration_name="document-semantic-config", + ) + + print("Docs containing 'PersonalizerClient' in the name (or other fields):") + for result in results: + print(" Title: {} (chunk {})".format(result["Title"], result["chunk"])) + # [END simple_query] + + +if __name__ == "__main__": + simple_text_query() diff --git a/sdk/search/azure-search-documents/samples/synonym_map.txt b/sdk/search/azure-search-documents/samples/synonym_map.txt new file mode 100644 index 000000000000..96f535332c9a --- /dev/null +++ b/sdk/search/azure-search-documents/samples/synonym_map.txt @@ -0,0 +1,2 @@ +USA, United States, United States of America +Washington, Wash. => WA \ No newline at end of file From 1007a06508a17d60a0671cc0f06b01c662f83674 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 24 Oct 2025 10:15:25 -0700 Subject: [PATCH 03/40] update --- .../documents/_operations/_operations.py | 18 ++++++++--------- .../azure/search/documents/_patch.py | 18 ++++++++++++++++- .../documents/aio/_operations/_operations.py | 18 ++++++++--------- .../indexes/_operations/_operations.py | 12 +++++------ .../indexes/aio/_operations/_operations.py | 10 +++++----- .../documents/indexes/models/_models.py | 20 +++++++++++++++++++ .../azure/search/documents/models/__init__.py | 4 ++-- .../azure/search/documents/models/_models.py | 2 +- 8 files changed, 69 insertions(+), 33 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index 282f90740feb..2b583c82c596 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -569,7 +569,7 @@ def get_document_count(self, *, query_source_authorization: Optional[str] = None }, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - def search_get( + def _search_get( self, *, search_text: Optional[str] = None, @@ -1078,7 +1078,7 @@ def get_document( return deserialized # type: ignore @distributed_trace - def suggest_get( + def _suggest_get( self, *, search_text: str, @@ -1373,7 +1373,7 @@ def suggest( @overload def index_documents( self, - batch: _models1.IndexBatch, + batch: _models1.IndexDocumentsBatch, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1382,7 +1382,7 @@ def index_documents( """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexBatch + :type batch: ~azure.search.documents.models.IndexDocumentsBatch :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1448,16 +1448,16 @@ def index_documents( @distributed_trace def index_documents( self, - batch: Union[_models1.IndexBatch, JSON, IO[bytes]], + batch: Union[_models1.IndexDocumentsBatch, JSON, IO[bytes]], *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> _models1.IndexDocumentsResult: """Sends a batch of document write actions to the index. - :param batch: The batch of index actions. Is one of the following types: IndexBatch, JSON, - IO[bytes] Required. - :type batch: ~azure.search.documents.models.IndexBatch or JSON or IO[bytes] + :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, + JSON, IO[bytes] Required. + :type batch: ~azure.search.documents.models.IndexDocumentsBatch or JSON or IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1529,7 +1529,7 @@ def index_documents( return deserialized # type: ignore @distributed_trace - def autocomplete_get( + def _autocomplete_get( self, *, search_text: str, diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index cbf30f0463a6..d611df824199 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -7,9 +7,21 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta from ._client import SearchClient as _SearchClient +class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + V2020_06_30 = "2020-06-30" + V2023_11_01 = "2023-11-01" + V2024_07_01 = "2024-07-01" + V2025_08_01_PREVIEW = "2025-08-01-preview" + + +DEFAULT_VERSION = ApiVersion.V2025_08_01_PREVIEW + + class SearchClient(_SearchClient): """SearchClient customizations go here.""" @@ -17,7 +29,11 @@ def __init__(self, endpoint, index_name, credential, **kwargs): super().__init__(endpoint, credential, index_name, **kwargs) -__all__: list[str] = ["SearchClient"] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [ + "SearchClient", + "ApiVersion", + "DEFAULT_VERSION", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index cd54121954c3..48ccdc120424 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -124,7 +124,7 @@ async def get_document_count(self, *, query_source_authorization: Optional[str] }, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - async def search_get( + async def _search_get( self, *, search_text: Optional[str] = None, @@ -633,7 +633,7 @@ async def get_document( return deserialized # type: ignore @distributed_trace_async - async def suggest_get( + async def _suggest_get( self, *, search_text: str, @@ -928,7 +928,7 @@ async def suggest( @overload async def index_documents( self, - batch: _models2.IndexBatch, + batch: _models2.IndexDocumentsBatch, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -937,7 +937,7 @@ async def index_documents( """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexBatch + :type batch: ~azure.search.documents.models.IndexDocumentsBatch :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1003,16 +1003,16 @@ async def index_documents( @distributed_trace_async async def index_documents( self, - batch: Union[_models2.IndexBatch, JSON, IO[bytes]], + batch: Union[_models2.IndexDocumentsBatch, JSON, IO[bytes]], *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> _models2.IndexDocumentsResult: """Sends a batch of document write actions to the index. - :param batch: The batch of index actions. Is one of the following types: IndexBatch, JSON, - IO[bytes] Required. - :type batch: ~azure.search.documents.models.IndexBatch or JSON or IO[bytes] + :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, + JSON, IO[bytes] Required. + :type batch: ~azure.search.documents.models.IndexDocumentsBatch or JSON or IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1084,7 +1084,7 @@ async def index_documents( return deserialized # type: ignore @distributed_trace_async - async def autocomplete_get( + async def _autocomplete_get( self, *, search_text: str, diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index 895baa0d7f80..a1c098ebbf2a 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -809,7 +809,7 @@ def build_search_index_create_knowledge_source_request(**kwargs: Any) -> HttpReq return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_list_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_search_index_get_service_statistics_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -828,7 +828,7 @@ def build_search_index_list_index_stats_summary_request(**kwargs: Any) -> HttpRe return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_get_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_search_index_list_index_stats_summary_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -4297,7 +4297,7 @@ def create_knowledge_source( return deserialized # type: ignore @distributed_trace - def list_index_stats_summary(self, **kwargs: Any) -> _models1.SearchServiceStatistics: + def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatistics: """Gets service level statistics for a search service. :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping @@ -4317,7 +4317,7 @@ def list_index_stats_summary(self, **kwargs: Any) -> _models1.SearchServiceStati cls: ClsType[_models1.SearchServiceStatistics] = kwargs.pop("cls", None) - _request = build_search_index_list_index_stats_summary_request( + _request = build_search_index_get_service_statistics_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -4360,7 +4360,7 @@ def list_index_stats_summary(self, **kwargs: Any) -> _models1.SearchServiceStati params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], ) - def get_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: + def list_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: """Retrieves a summary of statistics for all indexes in the search service. :return: An iterator like instance of IndexStatisticsSummary @@ -4384,7 +4384,7 @@ def get_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexSta def prepare_request(next_link=None): if not next_link: - _request = build_search_index_get_index_stats_summary_request( + _request = build_search_index_list_index_stats_summary_request( api_version=self._config.api_version, headers=_headers, params=_params, diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 1033ec6e37de..13ac36cc8a0f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -57,8 +57,8 @@ build_search_index_get_alias_request, build_search_index_get_index_request, build_search_index_get_index_statistics_request, - build_search_index_get_index_stats_summary_request, build_search_index_get_knowledge_source_request, + build_search_index_get_service_statistics_request, build_search_index_get_synonym_map_request, build_search_index_get_synonym_maps_request, build_search_index_list_agents_request, @@ -2954,7 +2954,7 @@ async def create_knowledge_source( return deserialized # type: ignore @distributed_trace_async - async def list_index_stats_summary(self, **kwargs: Any) -> _models2.SearchServiceStatistics: + async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceStatistics: """Gets service level statistics for a search service. :return: SearchServiceStatistics. The SearchServiceStatistics is compatible with MutableMapping @@ -2974,7 +2974,7 @@ async def list_index_stats_summary(self, **kwargs: Any) -> _models2.SearchServic cls: ClsType[_models2.SearchServiceStatistics] = kwargs.pop("cls", None) - _request = build_search_index_list_index_stats_summary_request( + _request = build_search_index_get_service_statistics_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -3017,7 +3017,7 @@ async def list_index_stats_summary(self, **kwargs: Any) -> _models2.SearchServic params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], ) - def get_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: + def list_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: """Retrieves a summary of statistics for all indexes in the search service. :return: An iterator like instance of IndexStatisticsSummary @@ -3041,7 +3041,7 @@ def get_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.Ind def prepare_request(next_link=None): if not next_link: - _request = build_search_index_get_index_stats_summary_request( + _request = build_search_index_list_index_stats_summary_request( api_version=self._config.api_version, headers=_headers, params=_params, diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index acb3d159f0af..25820f5df628 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -9476,6 +9476,8 @@ class SearchResourceEncryptionKey(_Model): resource, if the explicit identity is unspecified, it remains unchanged. If \"none\" is specified, the value of this property is cleared.""" + __flattened_items = ["application_id", "application_secret"] + @overload def __init__( self, @@ -9495,7 +9497,25 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.access_credentials is None: + return None + return getattr(self.access_credentials, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.access_credentials is None: + self.access_credentials = self._attr_to_rest_field["access_credentials"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) class SearchServiceCounters(_Model): diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 86d9675d77ac..8ac7e746260c 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -25,7 +25,7 @@ FacetResult, HybridSearch, IndexAction, - IndexBatch, + IndexDocumentsBatch, IndexDocumentsResult, IndexingResult, LookupDocument, @@ -95,7 +95,7 @@ "FacetResult", "HybridSearch", "IndexAction", - "IndexBatch", + "IndexDocumentsBatch", "IndexDocumentsResult", "IndexingResult", "LookupDocument", diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index bd774c1a79b5..d5ed32891a77 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -477,7 +477,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class IndexBatch(_Model): +class IndexDocumentsBatch(_Model): """Contains a batch of document write actions to send to the index. :ivar actions: The actions in the batch. Required. From 5ba584bae35d950f97ccbcaf4b1e3d9cf5d3a707 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 24 Oct 2025 10:20:44 -0700 Subject: [PATCH 04/40] update --- .../documents/_operations/_operations.py | 704 ++++++++++++++++-- .../documents/aio/_operations/_operations.py | 704 ++++++++++++++++-- .../azure/search/documents/models/__init__.py | 4 - .../azure/search/documents/models/_models.py | 240 ------ 4 files changed, 1310 insertions(+), 342 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index 2b583c82c596..c6c4bdacb9fc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -35,6 +35,7 @@ from .._validation import api_version_validation JSON = MutableMapping[str, Any] +_Unset: Any = object() T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -844,16 +845,46 @@ def _search_get( @overload def search( self, - search_request: _models1.SearchRequest, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[str] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + select: Optional[str] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + semantic_fields: Optional[str] = None, + vector_queries: Optional[list[_models1.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models1.VectorFilterMode]] = None, + hybrid_search: Optional[_models1.HybridSearch] = None, **kwargs: Any ) -> _models1.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Required. - :type search_request: ~azure.search.documents.models.SearchRequest :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -861,6 +892,143 @@ def search( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: str + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. Default value is None. + :paramtype search_fields: str + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". Default value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". Default value is None. + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields + marked as retrievable in the schema are included. Default value is None. + :paramtype select: str + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. Default value is + None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration_name: The name of a semantic configuration that will be used + when processing documents for queries of type semantic. Default value is None. + :paramtype semantic_configuration_name: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword answers: A value that specifies whether answers should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + Default value is None. + :paramtype semantic_fields: str + :keyword vector_queries: The query parameters for vector and hybrid search queries. Default + value is None. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". Default value is None. + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default + value is None. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SearchDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -869,7 +1037,7 @@ def search( @overload def search( self, - search_request: JSON, + body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -877,8 +1045,8 @@ def search( ) -> _models1.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Required. - :type search_request: JSON + :param body: Required. + :type body: JSON :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -894,7 +1062,7 @@ def search( @overload def search( self, - search_request: IO[bytes], + body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -902,8 +1070,8 @@ def search( ) -> _models1.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Required. - :type search_request: IO[bytes] + :param body: Required. + :type body: IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -919,20 +1087,189 @@ def search( @distributed_trace def search( self, - search_request: Union[_models1.SearchRequest, JSON, IO[bytes]], + body: Union[JSON, IO[bytes]] = _Unset, *, query_source_authorization: Optional[str] = None, + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + query_type: Optional[Union[str, _models1.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models1.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models1.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[str] = None, + search_mode: Optional[Union[str, _models1.SearchMode]] = None, + query_language: Optional[Union[str, _models1.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models1.QuerySpellerType]] = None, + select: Optional[str] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models1.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models1.QueryAnswerType]] = None, + captions: Optional[Union[str, _models1.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models1.QueryRewritesType]] = None, + semantic_fields: Optional[str] = None, + vector_queries: Optional[list[_models1.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models1.VectorFilterMode]] = None, + hybrid_search: Optional[_models1.HybridSearch] = None, **kwargs: Any ) -> _models1.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Is one of the following types: - SearchRequest, JSON, IO[bytes] Required. - :type search_request: ~azure.search.documents.models.SearchRequest or JSON or IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str + :keyword include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: str + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. Default value is None. + :paramtype search_fields: str + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". Default value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". Default value is None. + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields + marked as retrievable in the schema are included. Default value is None. + :paramtype select: str + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. Default value is + None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration_name: The name of a semantic configuration that will be used + when processing documents for queries of type semantic. Default value is None. + :paramtype semantic_configuration_name: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword answers: A value that specifies whether answers should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + Default value is None. + :paramtype semantic_fields: str + :keyword vector_queries: The query parameters for vector and hybrid search queries. Default + value is None. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". Default value is None. + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default + value is None. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SearchDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -951,12 +1288,49 @@ def search( content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SearchDocumentsResult] = kwargs.pop("cls", None) + if body is _Unset: + body = { + "answers": answers, + "captions": captions, + "count": include_total_count, + "debug": debug, + "facets": facets, + "filter": filter, + "highlight": highlight_fields, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "hybridSearch": hybrid_search, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "queryLanguage": query_language, + "queryRewrites": query_rewrites, + "queryType": query_type, + "scoringParameters": scoring_parameters, + "scoringProfile": scoring_profile, + "scoringStatistics": scoring_statistics, + "search": search_text, + "searchFields": search_fields, + "searchMode": search_mode, + "select": select, + "semanticConfiguration": semantic_configuration_name, + "semanticErrorHandling": semantic_error_handling, + "semanticFields": semantic_fields, + "semanticMaxWaitInMilliseconds": semantic_max_wait_in_milliseconds, + "semanticQuery": semantic_query, + "sessionId": session_id, + "skip": skip, + "speller": query_speller, + "top": top, + "vectorFilterMode": vector_filter_mode, + "vectorQueries": vector_queries, + } + body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None - if isinstance(search_request, (IOBase, bytes)): - _content = search_request + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(search_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_search_search_request( index_name=self._config.index_name, @@ -1215,16 +1589,30 @@ def _suggest_get( @overload def suggest( self, - suggest_request: _models1.SuggestRequest, *, + search_text: str, + suggester_name: str, query_source_authorization: Optional[str] = None, content_type: str = "application/json", + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models1.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1232,6 +1620,44 @@ def suggest( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: str + :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. Default value is None. + :paramtype select: str + :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. Default value is None. + :paramtype top: int :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1240,7 +1666,7 @@ def suggest( @overload def suggest( self, - suggest_request: JSON, + body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1248,8 +1674,8 @@ def suggest( ) -> _models1.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Required. - :type suggest_request: JSON + :param body: Required. + :type body: JSON :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1265,7 +1691,7 @@ def suggest( @overload def suggest( self, - suggest_request: IO[bytes], + body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1273,8 +1699,8 @@ def suggest( ) -> _models1.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Required. - :type suggest_request: IO[bytes] + :param body: Required. + :type body: IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1290,20 +1716,74 @@ def suggest( @distributed_trace def suggest( self, - suggest_request: Union[_models1.SuggestRequest, JSON, IO[bytes]], + body: Union[JSON, IO[bytes]] = _Unset, *, + search_text: str = _Unset, + suggester_name: str = _Unset, query_source_authorization: Optional[str] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models1.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Is one of the following types: SuggestRequest, - JSON, IO[bytes] Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest or JSON or IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: str + :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. Default value is None. + :paramtype select: str + :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. Default value is None. + :paramtype top: int :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1322,12 +1802,31 @@ def suggest( content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SuggestDocumentsResult] = kwargs.pop("cls", None) + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "search": search_text, + "searchFields": search_fields, + "select": select, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None - if isinstance(suggest_request, (IOBase, bytes)): - _content = suggest_request + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(suggest_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_search_suggest_request( index_name=self._config.index_name, @@ -1656,16 +2155,28 @@ def _autocomplete_get( @overload def autocomplete( self, - autocomplete_request: _models1.AutocompleteRequest, *, + search_text: str, + suggester_name: str, query_source_authorization: Optional[str] = None, content_type: str = "application/json", + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models1.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest + :keyword search_text: The search text on which to base autocomplete results. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1673,6 +2184,38 @@ def autocomplete( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will autocomplete terms even + if there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: str + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1681,7 +2224,7 @@ def autocomplete( @overload def autocomplete( self, - autocomplete_request: JSON, + body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1689,8 +2232,8 @@ def autocomplete( ) -> _models1.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: JSON + :param body: Required. + :type body: JSON :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1706,7 +2249,7 @@ def autocomplete( @overload def autocomplete( self, - autocomplete_request: IO[bytes], + body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1714,8 +2257,8 @@ def autocomplete( ) -> _models1.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: IO[bytes] + :param body: Required. + :type body: IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1731,21 +2274,66 @@ def autocomplete( @distributed_trace def autocomplete( self, - autocomplete_request: Union[_models1.AutocompleteRequest, JSON, IO[bytes]], + body: Union[JSON, IO[bytes]] = _Unset, *, + search_text: str = _Unset, + suggester_name: str = _Unset, query_source_authorization: Optional[str] = None, + autocomplete_mode: Optional[Union[str, _models1.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models1.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Is one of the - following types: AutocompleteRequest, JSON, IO[bytes] Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or JSON or - IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text on which to base autocomplete results. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will autocomplete terms even + if there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: str + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1764,12 +2352,30 @@ def autocomplete( content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.AutocompleteResult] = kwargs.pop("cls", None) + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "autocompleteMode": autocomplete_mode, + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "search": search_text, + "searchFields": search_fields, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None - if isinstance(autocomplete_request, (IOBase, bytes)): - _content = autocomplete_request + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(autocomplete_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_search_autocomplete_request( index_name=self._config.index_name, diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index 48ccdc120424..16b257d8734f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -45,6 +45,7 @@ from .._configuration import SearchClientConfiguration JSON = MutableMapping[str, Any] +_Unset: Any = object() T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -399,16 +400,46 @@ async def _search_get( @overload async def search( self, - search_request: _models2.SearchRequest, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + query_type: Optional[Union[str, _models2.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models2.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[str] = None, + search_mode: Optional[Union[str, _models2.SearchMode]] = None, + query_language: Optional[Union[str, _models2.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models2.QuerySpellerType]] = None, + select: Optional[str] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models2.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models2.QueryAnswerType]] = None, + captions: Optional[Union[str, _models2.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models2.QueryRewritesType]] = None, + semantic_fields: Optional[str] = None, + vector_queries: Optional[list[_models2.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models2.VectorFilterMode]] = None, + hybrid_search: Optional[_models2.HybridSearch] = None, **kwargs: Any ) -> _models2.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Required. - :type search_request: ~azure.search.documents.models.SearchRequest :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -416,6 +447,143 @@ async def search( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: str + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. Default value is None. + :paramtype search_fields: str + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". Default value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". Default value is None. + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields + marked as retrievable in the schema are included. Default value is None. + :paramtype select: str + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. Default value is + None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration_name: The name of a semantic configuration that will be used + when processing documents for queries of type semantic. Default value is None. + :paramtype semantic_configuration_name: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword answers: A value that specifies whether answers should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + Default value is None. + :paramtype semantic_fields: str + :keyword vector_queries: The query parameters for vector and hybrid search queries. Default + value is None. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". Default value is None. + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default + value is None. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SearchDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -424,7 +592,7 @@ async def search( @overload async def search( self, - search_request: JSON, + body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -432,8 +600,8 @@ async def search( ) -> _models2.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Required. - :type search_request: JSON + :param body: Required. + :type body: JSON :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -449,7 +617,7 @@ async def search( @overload async def search( self, - search_request: IO[bytes], + body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -457,8 +625,8 @@ async def search( ) -> _models2.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Required. - :type search_request: IO[bytes] + :param body: Required. + :type body: IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -474,20 +642,189 @@ async def search( @distributed_trace_async async def search( self, - search_request: Union[_models2.SearchRequest, JSON, IO[bytes]], + body: Union[JSON, IO[bytes]] = _Unset, *, query_source_authorization: Optional[str] = None, + include_total_count: Optional[bool] = None, + facets: Optional[list[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + query_type: Optional[Union[str, _models2.QueryType]] = None, + scoring_statistics: Optional[Union[str, _models2.ScoringStatistics]] = None, + session_id: Optional[str] = None, + scoring_parameters: Optional[list[str]] = None, + scoring_profile: Optional[str] = None, + debug: Optional[Union[str, _models2.QueryDebugMode]] = None, + search_text: Optional[str] = None, + search_fields: Optional[str] = None, + search_mode: Optional[Union[str, _models2.SearchMode]] = None, + query_language: Optional[Union[str, _models2.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models2.QuerySpellerType]] = None, + select: Optional[str] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + semantic_configuration_name: Optional[str] = None, + semantic_error_handling: Optional[Union[str, _models2.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + semantic_query: Optional[str] = None, + answers: Optional[Union[str, _models2.QueryAnswerType]] = None, + captions: Optional[Union[str, _models2.QueryCaptionType]] = None, + query_rewrites: Optional[Union[str, _models2.QueryRewritesType]] = None, + semantic_fields: Optional[str] = None, + vector_queries: Optional[list[_models2.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models2.VectorFilterMode]] = None, + hybrid_search: Optional[_models2.HybridSearch] = None, **kwargs: Any ) -> _models2.SearchDocumentsResult: """Searches for documents in the index. - :param search_request: The definition of the Search request. Is one of the following types: - SearchRequest, JSON, IO[bytes] Required. - :type search_request: ~azure.search.documents.models.SearchRequest or JSON or IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str + :keyword include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. Default value is None. + :paramtype include_total_count: bool + :keyword facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. Default value is None. + :paramtype facets: list[str] + :keyword filter: The OData $filter expression to apply to the search query. Default value is + None. + :paramtype filter: str + :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. Default value is None. + :paramtype highlight_fields: str + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is </em>. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is <em>. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", + "full", and "semantic". Default value is None. + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. Known + values are: "local" and "global". Default value is None. + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. Default value is None. + :paramtype session_id: str + :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). Default value is None. + :paramtype scoring_parameters: list[str] + :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. Default value is None. + :paramtype scoring_profile: str + :keyword debug: Enables a debugging tool that can be used to further explore your reranked + results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and + "all". Default value is None. + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. Default value is None. + :paramtype search_text: str + :keyword search_fields: The comma-separated list of field names to which to scope the full-text + search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the + field names of each fielded search expression take precedence over any field names listed in + this parameter. Default value is None. + :paramtype search_fields: str + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Known values are: "any" and "all". Default + value is None. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: A value that specifies the language of the search query. Known values + are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", + "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", + "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", + "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", + "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", + "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", + "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", + "te-in", and "ur-pk". Default value is None. + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Known values are: "none" and "lexicon". Default value is None. + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields + marked as retrievable in the schema are included. Default value is None. + :paramtype select: str + :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use skip due to this limitation, consider + using orderby on a totally-ordered key and filter with a range query instead. Default value is + None. + :paramtype skip: int + :keyword top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. Default value is None. + :paramtype top: int + :keyword semantic_configuration_name: The name of a semantic configuration that will be used + when processing documents for queries of type semantic. Default value is None. + :paramtype semantic_configuration_name: str + :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". Default value is None. + :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode + :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount + of time it takes for semantic enrichment to finish processing before the request fails. Default + value is None. + :paramtype semantic_max_wait_in_milliseconds: int + :keyword semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. Default value is None. + :paramtype semantic_query: str + :keyword answers: A value that specifies whether answers should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType + :keyword captions: A value that specifies whether captions should be returned as part of the + search response. Known values are: "none" and "extractive". Default value is None. + :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType + :keyword query_rewrites: A value that specifies whether query rewrites should be generated to + augment the search query. Known values are: "none" and "generative". Default value is None. + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. + Default value is None. + :paramtype semantic_fields: str + :keyword vector_queries: The query parameters for vector and hybrid search queries. Default + value is None. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter' for new indexes. Known values are: + "postFilter", "preFilter", and "strictPostFilter". Default value is None. + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default + value is None. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SearchDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -506,12 +843,49 @@ async def search( content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SearchDocumentsResult] = kwargs.pop("cls", None) + if body is _Unset: + body = { + "answers": answers, + "captions": captions, + "count": include_total_count, + "debug": debug, + "facets": facets, + "filter": filter, + "highlight": highlight_fields, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "hybridSearch": hybrid_search, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "queryLanguage": query_language, + "queryRewrites": query_rewrites, + "queryType": query_type, + "scoringParameters": scoring_parameters, + "scoringProfile": scoring_profile, + "scoringStatistics": scoring_statistics, + "search": search_text, + "searchFields": search_fields, + "searchMode": search_mode, + "select": select, + "semanticConfiguration": semantic_configuration_name, + "semanticErrorHandling": semantic_error_handling, + "semanticFields": semantic_fields, + "semanticMaxWaitInMilliseconds": semantic_max_wait_in_milliseconds, + "semanticQuery": semantic_query, + "sessionId": session_id, + "skip": skip, + "speller": query_speller, + "top": top, + "vectorFilterMode": vector_filter_mode, + "vectorQueries": vector_queries, + } + body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None - if isinstance(search_request, (IOBase, bytes)): - _content = search_request + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(search_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_search_search_request( index_name=self._config.index_name, @@ -770,16 +1144,30 @@ async def _suggest_get( @overload async def suggest( self, - suggest_request: _models2.SuggestRequest, *, + search_text: str, + suggester_name: str, query_source_authorization: Optional[str] = None, content_type: str = "application/json", + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models2.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -787,6 +1175,44 @@ async def suggest( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: str + :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. Default value is None. + :paramtype select: str + :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. Default value is None. + :paramtype top: int :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -795,7 +1221,7 @@ async def suggest( @overload async def suggest( self, - suggest_request: JSON, + body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -803,8 +1229,8 @@ async def suggest( ) -> _models2.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Required. - :type suggest_request: JSON + :param body: Required. + :type body: JSON :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -820,7 +1246,7 @@ async def suggest( @overload async def suggest( self, - suggest_request: IO[bytes], + body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -828,8 +1254,8 @@ async def suggest( ) -> _models2.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Required. - :type suggest_request: IO[bytes] + :param body: Required. + :type body: IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -845,20 +1271,74 @@ async def suggest( @distributed_trace_async async def suggest( self, - suggest_request: Union[_models2.SuggestRequest, JSON, IO[bytes]], + body: Union[JSON, IO[bytes]] = _Unset, *, + search_text: str = _Unset, + suggester_name: str = _Unset, query_source_authorization: Optional[str] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models2.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. - :param suggest_request: The Suggest request. Is one of the following types: SuggestRequest, - JSON, IO[bytes] Required. - :type suggest_request: ~azure.search.documents.models.SuggestRequest or JSON or IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str + :keyword filter: An OData expression that filters the documents considered for suggestions. + Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is + None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. Default value is None. + :paramtype order_by: str + :keyword search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. Default value is None. + :paramtype search_fields: str + :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. Default value is None. + :paramtype select: str + :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. Default value is None. + :paramtype top: int :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: @@ -877,12 +1357,31 @@ async def suggest( content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SuggestDocumentsResult] = kwargs.pop("cls", None) + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "orderby": order_by, + "search": search_text, + "searchFields": search_fields, + "select": select, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None - if isinstance(suggest_request, (IOBase, bytes)): - _content = suggest_request + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(suggest_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_search_suggest_request( index_name=self._config.index_name, @@ -1211,16 +1710,28 @@ async def _autocomplete_get( @overload async def autocomplete( self, - autocomplete_request: _models2.AutocompleteRequest, *, + search_text: str, + suggester_name: str, query_source_authorization: Optional[str] = None, content_type: str = "application/json", + autocomplete_mode: Optional[Union[str, _models2.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models2.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest + :keyword search_text: The search text on which to base autocomplete results. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1228,6 +1739,38 @@ async def autocomplete( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will autocomplete terms even + if there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: str + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1236,7 +1779,7 @@ async def autocomplete( @overload async def autocomplete( self, - autocomplete_request: JSON, + body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1244,8 +1787,8 @@ async def autocomplete( ) -> _models2.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: JSON + :param body: Required. + :type body: JSON :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1261,7 +1804,7 @@ async def autocomplete( @overload async def autocomplete( self, - autocomplete_request: IO[bytes], + body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", @@ -1269,8 +1812,8 @@ async def autocomplete( ) -> _models2.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Required. - :type autocomplete_request: IO[bytes] + :param body: Required. + :type body: IO[bytes] :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. @@ -1286,21 +1829,66 @@ async def autocomplete( @distributed_trace_async async def autocomplete( self, - autocomplete_request: Union[_models2.AutocompleteRequest, JSON, IO[bytes]], + body: Union[JSON, IO[bytes]] = _Unset, *, + search_text: str = _Unset, + suggester_name: str = _Unset, query_source_authorization: Optional[str] = None, + autocomplete_mode: Optional[Union[str, _models2.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, **kwargs: Any ) -> _models2.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. - :param autocomplete_request: The definition of the Autocomplete request. Is one of the - following types: AutocompleteRequest, JSON, IO[bytes] Required. - :type autocomplete_request: ~azure.search.documents.models.AutocompleteRequest or JSON or - IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword search_text: The search text on which to base autocomplete results. Required. + :paramtype search_text: str + :keyword suggester_name: The name of the suggester as specified in the suggesters collection + that's part of the index definition. Required. + :paramtype suggester_name: str :keyword query_source_authorization: Token identifying the user for which the query is being executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use + 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing + auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". + Default value is None. + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword filter: An OData expression that filters the documents used to produce completed terms + for the Autocomplete result. Default value is None. + :paramtype filter: str + :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will autocomplete terms even + if there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. Default value is None. + :paramtype use_fuzzy_matching: bool + :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_post_tag: str + :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. + :paramtype highlight_pre_tag: str + :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. Default value is None. + :paramtype minimum_coverage: float + :keyword search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. Default value + is None. + :paramtype search_fields: str + :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. Default value is None. + :paramtype top: int :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping :rtype: ~azure.search.documents.models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1319,12 +1907,30 @@ async def autocomplete( content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.AutocompleteResult] = kwargs.pop("cls", None) + if body is _Unset: + if search_text is _Unset: + raise TypeError("missing required argument: search_text") + if suggester_name is _Unset: + raise TypeError("missing required argument: suggester_name") + body = { + "autocompleteMode": autocomplete_mode, + "filter": filter, + "fuzzy": use_fuzzy_matching, + "highlightPostTag": highlight_post_tag, + "highlightPreTag": highlight_pre_tag, + "minimumCoverage": minimum_coverage, + "search": search_text, + "searchFields": search_fields, + "suggesterName": suggester_name, + "top": top, + } + body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None - if isinstance(autocomplete_request, (IOBase, bytes)): - _content = autocomplete_request + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(autocomplete_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_search_autocomplete_request( index_name=self._config.index_name, diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 8ac7e746260c..131c2175237c 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -15,7 +15,6 @@ from ._models import ( # type: ignore AutocompleteItem, - AutocompleteRequest, AutocompleteResult, DebugInfo, DocumentDebugInfo, @@ -44,7 +43,6 @@ SemanticDebugInfo, SingleVectorFieldResult, SuggestDocumentsResult, - SuggestRequest, SuggestResult, TextResult, VectorQuery, @@ -85,7 +83,6 @@ __all__ = [ "AutocompleteItem", - "AutocompleteRequest", "AutocompleteResult", "DebugInfo", "DocumentDebugInfo", @@ -114,7 +111,6 @@ "SemanticDebugInfo", "SingleVectorFieldResult", "SuggestDocumentsResult", - "SuggestRequest", "SuggestResult", "TextResult", "VectorQuery", diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index d5ed32891a77..49ef5bd5d8d6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -50,121 +50,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutocompleteRequest(_Model): - """Parameters for fuzzy matching, and other autocomplete query behaviors. - - :ivar search_text: The search text on which to base autocomplete results. Required. - :vartype search_text: str - :ivar autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - :vartype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :ivar filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the autocomplete - query. Default is false. When set to true, the query will autocomplete terms even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by an autocomplete query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. - :vartype search_fields: str - :ivar suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :vartype suggester_name: str - :ivar top: The number of auto-completed terms to retrieve. This must be a value between 1 and - 100. The default is 5. - :vartype top: int - """ - - search_text: str = rest_field(name="search", visibility=["read", "create", "update", "delete", "query"]) - """The search text on which to base autocomplete results. Required.""" - autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = rest_field( - name="autocompleteMode", visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies the mode for Autocomplete. The default is 'oneTerm'. Use 'twoTerms' to get shingles - and 'oneTermWithContext' to use the current context while producing auto-completed terms. Known - values are: \"oneTerm\", \"twoTerms\", and \"oneTermWithContext\".""" - filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An OData expression that filters the documents used to produce completed terms for the - Autocomplete result.""" - use_fuzzy_matching: Optional[bool] = rest_field( - name="fuzzy", visibility=["read", "create", "update", "delete", "query"] - ) - """A value indicating whether to use fuzzy matching for the autocomplete query. Default is false. - When set to true, the query will autocomplete terms even if there's a substituted or missing - character in the search text. While this provides a better experience in some scenarios, it - comes at a performance cost as fuzzy autocomplete queries are slower and consume more - resources.""" - highlight_post_tag: Optional[str] = rest_field( - name="highlightPostTag", visibility=["read", "create", "update", "delete", "query"] - ) - """A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, - hit highlighting is disabled.""" - highlight_pre_tag: Optional[str] = rest_field( - name="highlightPreTag", visibility=["read", "create", "update", "delete", "query"] - ) - """A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If - omitted, hit highlighting is disabled.""" - minimum_coverage: Optional[float] = rest_field( - name="minimumCoverage", visibility=["read", "create", "update", "delete", "query"] - ) - """A number between 0 and 100 indicating the percentage of the index that must be covered by an - autocomplete query in order for the query to be reported as a success. This parameter can be - useful for ensuring search availability even for services with only one replica. The default is - 80.""" - search_fields: Optional[str] = rest_field( - name="searchFields", visibility=["read", "create", "update", "delete", "query"] - ) - """The comma-separated list of field names to consider when querying for auto-completed terms. - Target fields must be included in the specified suggester.""" - suggester_name: str = rest_field(name="suggesterName", visibility=["read", "create", "update", "delete", "query"]) - """The name of the suggester as specified in the suggesters collection that's part of the index - definition. Required.""" - top: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of auto-completed terms to retrieve. This must be a value between 1 and 100. The - default is 5.""" - - @overload - def __init__( - self, - *, - search_text: str, - suggester_name: str, - autocomplete_mode: Optional[Union[str, "_models.AutocompleteMode"]] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - search_fields: Optional[str] = None, - top: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class AutocompleteResult(_Model): """The result of Autocomplete query. @@ -1533,131 +1418,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SuggestRequest(_Model): - """Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors. - - :ivar filter: An OData expression that filters the documents considered for suggestions. - :vartype filter: str - :ivar use_fuzzy_matching: A value indicating whether to use fuzzy matching for the suggestion - query. Default is false. When set to true, the query will find suggestions even if there's a - substituted or missing character in the search text. While this provides a better experience in - some scenarios, it comes at a performance cost as fuzzy suggestion searches are slower and - consume more resources. - :vartype use_fuzzy_matching: bool - :ivar highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_post_tag: str - :ivar highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - :vartype highlight_pre_tag: str - :ivar minimum_coverage: A number between 0 and 100 indicating the percentage of the index that - must be covered by a suggestion query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. - :vartype minimum_coverage: float - :ivar order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. - :vartype order_by: str - :ivar search_text: The search text to use to suggest documents. Must be at least 1 character, - and no more than 100 characters. Required. - :vartype search_text: str - :ivar search_fields: The comma-separated list of field names to search for the specified search - text. Target fields must be included in the specified suggester. - :vartype search_fields: str - :ivar select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. - :vartype select: str - :ivar suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :vartype suggester_name: str - :ivar top: The number of suggestions to retrieve. This must be a value between 1 and 100. The - default is 5. - :vartype top: int - """ - - filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An OData expression that filters the documents considered for suggestions.""" - use_fuzzy_matching: Optional[bool] = rest_field( - name="fuzzy", visibility=["read", "create", "update", "delete", "query"] - ) - """A value indicating whether to use fuzzy matching for the suggestion query. Default is false. - When set to true, the query will find suggestions even if there's a substituted or missing - character in the search text. While this provides a better experience in some scenarios, it - comes at a performance cost as fuzzy suggestion searches are slower and consume more resources.""" - highlight_post_tag: Optional[str] = rest_field( - name="highlightPostTag", visibility=["read", "create", "update", "delete", "query"] - ) - """A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, - hit highlighting of suggestions is disabled.""" - highlight_pre_tag: Optional[str] = rest_field( - name="highlightPreTag", visibility=["read", "create", "update", "delete", "query"] - ) - """A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If - omitted, hit highlighting of suggestions is disabled.""" - minimum_coverage: Optional[float] = rest_field( - name="minimumCoverage", visibility=["read", "create", "update", "delete", "query"] - ) - """A number between 0 and 100 indicating the percentage of the index that must be covered by a - suggestion query in order for the query to be reported as a success. This parameter can be - useful for ensuring search availability even for services with only one replica. The default is - 80.""" - order_by: Optional[str] = rest_field(name="orderby", visibility=["read", "create", "update", "delete", "query"]) - """The comma-separated list of OData $orderby expressions by which to sort the results. Each - expression can be either a field name or a call to either the geo.distance() or the - search.score() functions. Each expression can be followed by asc to indicate ascending, or desc - to indicate descending. The default is ascending order. Ties will be broken by the match scores - of documents. If no $orderby is specified, the default sort order is descending by document - match score. There can be at most 32 $orderby clauses.""" - search_text: str = rest_field(name="search", visibility=["read", "create", "update", "delete", "query"]) - """The search text to use to suggest documents. Must be at least 1 character, and no more than 100 - characters. Required.""" - search_fields: Optional[str] = rest_field( - name="searchFields", visibility=["read", "create", "update", "delete", "query"] - ) - """The comma-separated list of field names to search for the specified search text. Target fields - must be included in the specified suggester.""" - select: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The comma-separated list of fields to retrieve. If unspecified, only the key field will be - included in the results.""" - suggester_name: str = rest_field(name="suggesterName", visibility=["read", "create", "update", "delete", "query"]) - """The name of the suggester as specified in the suggesters collection that's part of the index - definition. Required.""" - top: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of suggestions to retrieve. This must be a value between 1 and 100. The default is - 5.""" - - @overload - def __init__( - self, - *, - search_text: str, - suggester_name: str, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - use_fuzzy_matching: Optional[bool] = None, - highlight_post_tag: Optional[str] = None, - highlight_pre_tag: Optional[str] = None, - minimum_coverage: Optional[float] = None, - order_by: Optional[str] = None, - search_fields: Optional[str] = None, - select: Optional[str] = None, - top: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class SuggestResult(_Model): """A result containing a document found by a suggestion query, plus associated metadata. From 2cb6b7a8c86ede86ddb250b957b332ed81d1af53 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 24 Oct 2025 16:28:13 -0700 Subject: [PATCH 05/40] add tests --- .../async_tests/test_buffered_sender_async.py | 159 ++ .../async_tests/test_search_client_async.py | 30 + .../test_search_client_basic_live_async.py | 45 + ...earch_client_buffered_sender_live_async.py | 173 ++ ...search_client_index_document_live_async.py | 169 ++ .../test_search_client_search_live_async.py | 160 ++ ...st_search_index_client_alias_live_async.py | 111 ++ .../test_search_index_client_async.py | 114 ++ ...rch_index_client_data_source_live_async.py | 120 ++ .../test_search_index_client_live_async.py | 190 +++ ...search_index_client_skillset_live_async.py | 217 +++ ...rch_index_client_synonym_map_live_async.py | 147 ++ .../test_search_indexer_client_live_async.py | 154 ++ .../azure-search-documents/tests/conftest.py | 36 + .../tests/hotel_large.json | 1504 +++++++++++++++++ .../tests/hotel_schema.json | 288 ++++ .../tests/hotel_small.json | 254 +++ .../tests/perfstress_tests/README.md | 47 + .../tests/perfstress_tests/__init__.py | 0 .../tests/perfstress_tests/autocomplete.py | 55 + .../perfstress_tests/search_documents.py | 56 + .../tests/perfstress_tests/suggest.py | 55 + .../tests/search_service_preparer.py | 158 ++ .../tests/test_buffered_sender.py | 154 ++ .../tests/test_index_documents_batch.py | 69 + .../tests/test_index_field_helpers.py | 90 + .../tests/test_models.py | 45 + .../tests/test_queries.py | 165 ++ .../tests/test_regex_flags.py | 102 ++ .../tests/test_search_client.py | 323 ++++ .../tests/test_search_client_basic_live.py | 41 + ...test_search_client_buffered_sender_live.py | 168 ++ .../test_search_client_index_document_live.py | 167 ++ .../tests/test_search_client_search_live.py | 134 ++ .../tests/test_search_index_client.py | 130 ++ .../test_search_index_client_alias_live.py | 108 ++ ...st_search_index_client_data_source_live.py | 136 ++ .../tests/test_search_index_client_live.py | 185 ++ .../test_search_index_client_skillset_live.py | 252 +++ ...st_search_index_client_synonym_map_live.py | 145 ++ .../tests/test_search_indexer_client_live.py | 158 ++ .../tests/test_serialization.py | 108 ++ 42 files changed, 6922 insertions(+) create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py create mode 100644 sdk/search/azure-search-documents/tests/conftest.py create mode 100644 sdk/search/azure-search-documents/tests/hotel_large.json create mode 100644 sdk/search/azure-search-documents/tests/hotel_schema.json create mode 100644 sdk/search/azure-search-documents/tests/hotel_small.json create mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/README.md create mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/__init__.py create mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py create mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py create mode 100644 sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py create mode 100644 sdk/search/azure-search-documents/tests/search_service_preparer.py create mode 100644 sdk/search/azure-search-documents/tests/test_buffered_sender.py create mode 100644 sdk/search/azure-search-documents/tests/test_index_documents_batch.py create mode 100644 sdk/search/azure-search-documents/tests/test_index_field_helpers.py create mode 100644 sdk/search/azure-search-documents/tests/test_models.py create mode 100644 sdk/search/azure-search-documents/tests/test_queries.py create mode 100644 sdk/search/azure-search-documents/tests/test_regex_flags.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_client.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_client_basic_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_client_search_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py create mode 100644 sdk/search/azure-search-documents/tests/test_serialization.py diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py new file mode 100644 index 000000000000..3c166e74983c --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_buffered_sender_async.py @@ -0,0 +1,159 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from unittest import mock +import pytest +from azure.search.documents.aio import ( + SearchIndexingBufferedSender, +) +from azure.core.credentials import AzureKeyCredential +from azure.core.exceptions import HttpResponseError, ServiceResponseTimeoutError +from azure.search.documents.models import IndexingResult +from test_search_index_client_async import await_prepared_test + +CREDENTIAL = AzureKeyCredential(key="test_api_key") + + +class TestSearchBatchingClientAsync: + @await_prepared_test + async def test_search_indexing_buffered_sender_kwargs(self): + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, window=100) as client: + assert client._batch_action_count == 512 + assert client._max_retries_per_action == 3 + assert client._auto_flush_interval == 60 + assert client._auto_flush + + @await_prepared_test + async def test_batch_queue(self): + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + assert client._index_documents_batch + await client.upload_documents(["upload1"]) + await client.delete_documents(["delete1", "delete2"]) + await client.merge_documents(["merge1", "merge2", "merge3"]) + await client.merge_or_upload_documents(["merge_or_upload1"]) + assert len(client.actions) == 7 + actions = await client._index_documents_batch.dequeue_actions() + assert len(client.actions) == 0 + await client._index_documents_batch.enqueue_actions(actions) + assert len(client.actions) == 7 + + @await_prepared_test + @mock.patch( + "azure.search.documents.aio._search_indexing_buffered_sender_async.SearchIndexingBufferedSender._process_if_needed" + ) + async def test_process_if_needed(self, mock_process_if_needed): + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL) as client: + await client.upload_documents(["upload1"]) + await client.delete_documents(["delete1", "delete2"]) + assert mock_process_if_needed.called + + @await_prepared_test + @mock.patch( + "azure.search.documents.aio._search_indexing_buffered_sender_async.SearchIndexingBufferedSender._cleanup" + ) + async def test_context_manager(self, mock_cleanup): + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + await client.upload_documents(["upload1"]) + await client.delete_documents(["delete1", "delete2"]) + assert mock_cleanup.called + + @await_prepared_test + async def test_flush(self): + DOCUMENT = { + "category": "Hotel", + "hotelId": "1000", + "rating": 4.0, + "rooms": [], + "hotelName": "Azure Inn", + } + with mock.patch.object( + SearchIndexingBufferedSender, + "_index_documents_actions", + side_effect=HttpResponseError("Error"), + ): + async with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + client._index_key = "hotelId" + await client.upload_documents([DOCUMENT]) + await client.flush() + assert len(client.actions) == 0 + + @await_prepared_test + async def test_callback_new(self): + on_new = mock.AsyncMock() + async with SearchIndexingBufferedSender( + "endpoint", "index name", CREDENTIAL, auto_flush=False, on_new=on_new + ) as client: + await client.upload_documents(["upload1"]) + assert on_new.called + + @await_prepared_test + async def test_callback_error(self): + async def mock_fail_index_documents(actions, timeout=86400): + if len(actions) > 0: + result = IndexingResult() + result.key = actions[0].additional_properties.get("id") + result.status_code = 400 + result.succeeded = False + self.uploaded = self.uploaded + len(actions) - 1 + return [result] + + on_error = mock.AsyncMock() + async with SearchIndexingBufferedSender( + "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error + ) as client: + client._index_documents_actions = mock_fail_index_documents + client._index_key = "id" + await client.upload_documents({"id": 0}) + await client.flush() + assert on_error.called + + @await_prepared_test + async def test_callback_error_on_timeout(self): + async def mock_fail_index_documents(actions, timeout=86400): + if len(actions) > 0: + result = IndexingResult() + result.key = actions[0].additional_properties.get("id") + result.status_code = 400 + result.succeeded = False + self.uploaded = self.uploaded + len(actions) - 1 + time.sleep(1) + return [result] + + on_error = mock.AsyncMock() + async with SearchIndexingBufferedSender( + "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error + ) as client: + client._index_documents_actions = mock_fail_index_documents + client._index_key = "id" + await client.upload_documents([{"id": 0}, {"id": 1}]) + with pytest.raises(ServiceResponseTimeoutError): + await client.flush(timeout=-1) + assert on_error.call_count == 2 + + @await_prepared_test + async def test_callback_progress(self): + async def mock_successful_index_documents(actions, timeout=86400): + if len(actions) > 0: + result = IndexingResult() + result.key = actions[0].additional_properties.get("id") + result.status_code = 200 + result.succeeded = True + return [result] + + on_progress = mock.AsyncMock() + on_remove = mock.AsyncMock() + async with SearchIndexingBufferedSender( + "endpoint", + "index name", + CREDENTIAL, + auto_flush=False, + on_progress=on_progress, + on_remove=on_remove, + ) as client: + client._index_documents_actions = mock_successful_index_documents + client._index_key = "id" + await client.upload_documents({"id": 0}) + await client.flush() + assert on_progress.called + assert on_remove.called diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py new file mode 100644 index 000000000000..c41691889a96 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_async.py @@ -0,0 +1,30 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from unittest import mock +from azure.core.credentials import AzureKeyCredential +from azure.search.documents._generated.models import SearchDocumentsResult, SearchResult +from azure.search.documents.aio import SearchClient +from azure.search.documents.aio._search_client_async import AsyncSearchPageIterator +from test_search_index_client_async import await_prepared_test + +CREDENTIAL = AzureKeyCredential(key="test_api_key") + + +class TestSearchClientAsync: + @await_prepared_test + @mock.patch( + "azure.search.documents._generated.aio.operations._documents_operations.DocumentsOperations.search_post" + ) + async def test_get_count_reset_continuation_token(self, mock_search_post): + client = SearchClient("endpoint", "index name", CREDENTIAL) + result = await client.search(search_text="search text") + assert result._page_iterator_class is AsyncSearchPageIterator + search_result = SearchDocumentsResult() + search_result.results = [SearchResult(additional_properties={"key": "val"})] + mock_search_post.return_value = search_result + await result.__anext__() + result._first_page_iterator_instance.continuation_token = "fake token" + await result.get_count() + assert not result._first_page_iterator_instance.continuation_token diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py new file mode 100644 index 000000000000..59a7835e4c8b --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_basic_live_async.py @@ -0,0 +1,45 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core.exceptions import HttpResponseError +from azure.search.documents.aio import SearchClient +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClientAsync(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_get_document_count(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(is_async=True)) + async with client: + assert await client.get_document_count() == 10 + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_get_document(self, endpoint, index_name, index_batch): + client = SearchClient(endpoint, index_name, get_credential(is_async=True)) + async with client: + for hotel_id in range(1, 11): + result = await client.get_document(key=str(hotel_id)) + expected = index_batch["value"][hotel_id - 1] + assert result.get("hotelId") == expected.get("hotelId") + assert result.get("hotelName") == expected.get("hotelName") + assert result.get("description") == expected.get("description") + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_get_document_missing(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(is_async=True)) + async with client: + with pytest.raises(HttpResponseError): + await client.get_document(key="1000") diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py new file mode 100644 index 000000000000..05ad3b2a6bdd --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_buffered_sender_live_async.py @@ -0,0 +1,173 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +import time +from azure.core.exceptions import HttpResponseError +from azure.core.credentials import AzureKeyCredential +from azure.search.documents.aio import SearchIndexingBufferedSender, SearchClient +from devtools_testutils import AzureRecordedTestCase, get_credential +from devtools_testutils.aio import recorded_by_proxy_async +from search_service_preparer import SearchEnvVarPreparer, search_decorator + +TIME_TO_SLEEP = 3 + + +class TestSearchIndexingBufferedSenderAsync(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_search_client_index_buffered_sender(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) + batch_client = SearchIndexingBufferedSender( + endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60 + ) + try: + async with client: + async with batch_client: + doc_count = 10 + doc_count = await self._test_upload_documents_new(client, batch_client, doc_count) + doc_count = await self._test_upload_documents_existing(client, batch_client, doc_count) + doc_count = await self._test_delete_documents_existing(client, batch_client, doc_count) + doc_count = await self._test_delete_documents_missing(client, batch_client, doc_count) + doc_count = await self._test_merge_documents_existing(client, batch_client, doc_count) + doc_count = await self._test_merge_documents_missing(client, batch_client, doc_count) + doc_count = await self._test_merge_or_upload_documents(client, batch_client, doc_count) + finally: + await batch_client.close() + + async def _test_upload_documents_new(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + docs = [ + {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + await batch_client.upload_documents(docs) + doc_count += 2 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + for doc in docs: + result = await client.get_document(key=doc["hotelId"]) + assert result["hotelId"] == doc["hotelId"] + assert result["hotelName"] == doc["hotelName"] + assert result["rating"] == doc["rating"] + assert result["rooms"] == doc["rooms"] + return doc_count + + async def _test_upload_documents_existing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # add one new and one existing + docs = [ + {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + await batch_client.upload_documents(docs) + doc_count += 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + return doc_count + + async def _test_delete_documents_existing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + docs = [{"hotelId": "3"}, {"hotelId": "4"}] + await batch_client.delete_documents(docs) + doc_count -= 2 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + await client.get_document(key="3") + + with pytest.raises(HttpResponseError): + await client.get_document(key="4") + return doc_count + + async def _test_delete_documents_missing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # delete one existing and one missing + docs = [{"hotelId": "1003"}, {"hotelId": "2"}] + await batch_client.delete_documents(docs) + doc_count -= 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + with pytest.raises(HttpResponseError): + await client.get_document(key="1003") + with pytest.raises(HttpResponseError): + await client.get_document(key="2") + return doc_count + + async def _test_merge_documents_existing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] + await batch_client.merge_documents(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + result = await client.get_document(key="5") + assert result["rating"] == 1 + + result = await client.get_document(key="6") + assert result["rating"] == 2 + return doc_count + + async def _test_merge_documents_missing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # merge to one existing and one missing document + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + await batch_client.merge_documents(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + await client.get_document(key="1003") + + result = await client.get_document(key="1") + assert result["rating"] == 2 + return doc_count + + async def _test_merge_or_upload_documents(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # merge to one existing and one missing + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + await batch_client.merge_or_upload_documents(docs) + doc_count += 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + result = await client.get_document(key="1003") + assert result["rating"] == 1 + + result = await client.get_document(key="1") + assert result["rating"] == 2 + return doc_count diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py new file mode 100644 index 000000000000..c021c11c6fb8 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_index_document_live_async.py @@ -0,0 +1,169 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from pydoc import doc +import pytest +import time +from azure.core.exceptions import HttpResponseError +from azure.search.documents.aio import SearchClient +from devtools_testutils import AzureRecordedTestCase, get_credential +from devtools_testutils.aio import recorded_by_proxy_async +from search_service_preparer import SearchEnvVarPreparer, search_decorator + +TIME_TO_SLEEP = 3 + + +class TestSearchClientDocumentsAsync(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_search_client_index_document(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) + doc_count = 10 + async with client: + doc_count = await self._test_upload_documents_new(client, doc_count) + doc_count = await self._test_upload_documents_existing(client, doc_count) + doc_count = await self._test_delete_documents_existing(client, doc_count) + doc_count = await self._test_delete_documents_missing(client, doc_count) + doc_count = await self._test_merge_documents_existing(client, doc_count) + doc_count = await self._test_merge_documents_missing(client, doc_count) + doc_count = await self._test_merge_or_upload_documents(client, doc_count) + + async def _test_upload_documents_new(self, client, doc_count): + docs = [ + {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + results = await client.upload_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {201} + doc_count += len(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + for doc in docs: + result = await client.get_document(key=doc["hotelId"]) + assert result["hotelId"] == doc["hotelId"] + assert result["hotelName"] == doc["hotelName"] + assert result["rating"] == doc["rating"] + assert result["rooms"] == doc["rooms"] + return doc_count + + async def _test_upload_documents_existing(self, client, doc_count): + # add one new and one existing + docs = [ + {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + results = await client.upload_documents(docs) + assert len(results) == len(docs) + doc_count += 1 + assert set(x.status_code for x in results) == {200, 201} + return doc_count + + async def _test_delete_documents_existing(self, client, doc_count): + docs = [{"hotelId": "3"}, {"hotelId": "4"}] + results = await client.delete_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200} + doc_count -= len(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + await client.get_document(key="3") + + with pytest.raises(HttpResponseError): + await client.get_document(key="4") + return doc_count + + async def _test_delete_documents_missing(self, client, doc_count): + # delete one existing and one missing + docs = [{"hotelId": "1003"}, {"hotelId": "2"}] + results = await client.delete_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200} + doc_count -= 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + await client.get_document(key="1003") + + with pytest.raises(HttpResponseError): + await client.get_document(key="2") + return doc_count + + async def _test_merge_documents_existing(self, client, doc_count): + docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] + results = await client.merge_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200} + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + result = await client.get_document(key="5") + assert result["rating"] == 1 + + result = await client.get_document(key="6") + assert result["rating"] == 2 + return doc_count + + async def _test_merge_documents_missing(self, client, doc_count): + # merge to one existing and one missing document + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + results = await client.merge_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200, 404} + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + await client.get_document(key="1003") + + result = await client.get_document(key="1") + assert result["rating"] == 2 + return doc_count + + async def _test_merge_or_upload_documents(self, client, doc_count): + # merge to one existing and one missing + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + results = await client.merge_or_upload_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200, 201} + doc_count += 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert await client.get_document_count() == doc_count + + result = await client.get_document(key="1003") + assert result["rating"] == 1 + + result = await client.get_document(key="1") + assert result["rating"] == 2 + return doc_count diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py new file mode 100644 index 000000000000..e7e31c666197 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py @@ -0,0 +1,160 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import pytest + +from azure.core.exceptions import HttpResponseError +from azure.search.documents.aio import SearchClient +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestClientTestAsync(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_search_client(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(is_async=True), retry_backoff_factor=60) + async with client: + await self._test_get_search_simple(client) + await self._test_get_search_simple_with_top(client) + await self._test_get_search_filter(client) + await self._test_get_search_filter_array(client) + await self._test_get_search_counts(client) + await self._test_get_search_coverage(client) + await self._test_get_search_facets_none(client) + await self._test_get_search_facets_result(client) + await self._test_autocomplete(client) + await self._test_suggest(client) + + async def _test_get_search_simple(self, client): + results = [] + async for x in await client.search(search_text="hotel"): + results.append(x) + assert len(results) == 7 + + results = [] + async for x in await client.search(search_text="motel"): + results.append(x) + assert len(results) == 2 + + async def _test_get_search_simple_with_top(self, client): + results = [] + async for x in await client.search(search_text="hotel", top=3): + results.append(x) + assert len(results) == 3 + + results = [] + async for x in await client.search(search_text="motel", top=3): + results.append(x) + assert len(results) == 2 + + async def _test_get_search_filter(self, client): + results = [] + select = ["hotelName", "category", "description"] + async for x in await client.search( + search_text="WiFi", + filter="category eq 'Budget'", + select=",".join(select), + order_by="hotelName desc", + ): + results.append(x) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) + expected = { + "category", + "hotelName", + "description", + "@search.score", + "@search.reranker_score", + "@search.highlights", + "@search.captions", + "@search.document_debug_info", + "@search.reranker_boosted_score", + } + assert all(set(x) == expected for x in results) + assert all(x["category"] == "Budget" for x in results) + + async def _test_get_search_filter_array(self, client): + results = [] + select = ["hotelName", "category", "description"] + async for x in await client.search( + search_text="WiFi", + filter="category eq 'Budget'", + select=select, + order_by="hotelName desc", + ): + results.append(x) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) + expected = { + "category", + "hotelName", + "description", + "@search.score", + "@search.reranker_score", + "@search.highlights", + "@search.captions", + "@search.document_debug_info", + "@search.reranker_boosted_score", + } + assert all(set(x) == expected for x in results) + assert all(x["category"] == "Budget" for x in results) + + async def _test_get_search_counts(self, client): + results = await client.search(search_text="hotel") + assert await results.get_count() is None + + results = await client.search(search_text="hotel", include_total_count=True) + assert await results.get_count() == 7 + + async def _test_get_search_coverage(self, client): + results = await client.search(search_text="hotel") + assert await results.get_coverage() is None + + results = await client.search(search_text="hotel", minimum_coverage=50.0) + cov = await results.get_coverage() + assert isinstance(cov, float) + assert cov >= 50.0 + + async def _test_get_search_facets_none(self, client): + select = ("hotelName", "category", "description") + results = await client.search(search_text="WiFi", select=",".join(select)) + assert await results.get_facets() is None + + async def _test_get_search_facets_result(self, client): + select = ("hotelName", "category", "description") + results = await client.search(search_text="WiFi", facets=["category"], select=",".join(select)) + assert await results.get_facets() == { + "category": [ + {"value": "Budget", "count": 4}, + {"value": "Luxury", "count": 1}, + ] + } + + async def _test_autocomplete(self, client): + results = await client.autocomplete(search_text="mot", suggester_name="sg") + assert results == [{"text": "motel", "query_plus_text": "motel"}] + + async def _test_suggest(self, client): + results = await client.suggest(search_text="mot", suggester_name="sg") + assert results == [ + {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, + {"hotelId": "9", "text": "Secret Point Motel"}, + ] + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_large.json") + @recorded_by_proxy_async + async def test_search_client_large(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(is_async=True)) + async with client: + await self._test_get_search_simple_large(client) + + async def _test_get_search_simple_large(self, client): + results = [] + async for x in await client.search(search_text=""): + results.append(x) + assert len(results) == 60 diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py new file mode 100644 index 000000000000..6fdfe85ae2ba --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_alias_live_async.py @@ -0,0 +1,111 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from unicodedata import name +import pytest + +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes.aio import SearchIndexClient +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential +from azure.search.documents.indexes.models import ( + AnalyzeTextOptions, + CorsOptions, + SearchIndex, + ScoringProfile, + SimpleField, + SearchFieldDataType, + SearchAlias, +) + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClientAlias(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_alias(self, endpoint): + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + aliases = ["resort", "motel"] + + async with client: + index_name = await client.list_index_names().__anext__() + await self._test_list_aliases_empty(client) + await self._test_create_alias(client, aliases[0], index_name) + + await self._test_create_or_update_alias(client, aliases[1], index_name) + + # point an old alias to a new index + new_index_name = "hotel" + await self._test_update_alias_to_new_index(client, aliases[1], new_index_name, index_name) + + await self._test_get_alias(client, aliases) + + await self._test_list_aliases(client, aliases) + await self._test_delete_aliases(client) + + async def _test_list_aliases_empty(self, client): + result = client.list_aliases() + with pytest.raises(StopAsyncIteration): + await result.__anext__() + + async def _test_create_alias(self, client, alias_name, index_name): + alias = SearchAlias(name=alias_name, indexes=[index_name]) + result = await client.create_alias(alias) + assert result.name == alias_name + assert set(result.indexes) == {index_name} + + async def _test_create_or_update_alias(self, client, alias_name, index_name): + alias = SearchAlias(name=alias_name, indexes=[index_name]) + result = await client.create_or_update_alias(alias) + assert result.name == alias_name + assert set(result.indexes) == {index_name} + + async def _test_update_alias_to_new_index(self, client, alias_name, new_index, old_index): + await self._create_index(client, new_index) + alias = SearchAlias(name=alias_name, indexes=[new_index]) + result = await client.create_or_update_alias(alias) + + assert result.name == alias_name + assert result.indexes[0] != old_index + assert result.indexes[0] == new_index + + async def _test_get_alias(self, client, aliases): + for alias in aliases: + result = await client.get_alias(alias) + assert result + assert result.name == alias + + async def _test_list_aliases(self, client, aliases): + result = {alias async for alias in client.list_alias_names()} + assert result == set(aliases) + + async def _test_delete_aliases(self, client): + aliases = [alias async for alias in client.list_aliases()] + + for alias in aliases: + await client.delete_alias(alias) + with pytest.raises(HttpResponseError): + result = await client.get_alias(alias) + + async def _create_index(self, client, index_name): + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=index_name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = await client.create_index(index) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py new file mode 100644 index 000000000000..473555cf29a1 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_async.py @@ -0,0 +1,114 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import functools +import pytest +from unittest import mock +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import ApiVersion +from azure.search.documents.aio import SearchClient +from azure.search.documents.indexes.aio import SearchIndexClient, SearchIndexerClient +from devtools_testutils import trim_kwargs_from_test_function + +CREDENTIAL = AzureKeyCredential(key="test_api_key") + + +def await_prepared_test(test_fn): + """Synchronous wrapper for async test methods. Used to avoid making changes + upstream to AbstractPreparer (which doesn't await the functions it wraps) + """ + + @functools.wraps(test_fn) + def run(test_class_instance, *args, **kwargs): + trim_kwargs_from_test_function(test_fn, kwargs) + loop = asyncio.get_event_loop() + return loop.run_until_complete(test_fn(test_class_instance, **kwargs)) + + return run + + +class TestSearchIndexClient: + def test_index_init(self): + client = SearchIndexClient("endpoint", CREDENTIAL) + assert client._headers == { + "api-key": "test_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_index_credential_roll(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential) + assert client._headers == { + "api-key": "old_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + credential.update("new_api_key") + assert client._headers == { + "api-key": "new_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_get_search_client(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential) + search_client = client.get_search_client("index") + assert isinstance(search_client, SearchClient) + + def test_get_search_client_inherit_api_version(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential, api_version=ApiVersion.V2020_06_30) + search_client = client.get_search_client("index") + assert isinstance(search_client, SearchClient) + assert search_client._api_version == ApiVersion.V2020_06_30 + + def test_index_endpoint_https(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential) + assert client._endpoint.startswith("https") + + client = SearchIndexClient("https://endpoint", credential) + assert client._endpoint.startswith("https") + + with pytest.raises(ValueError): + client = SearchIndexClient("http://endpoint", credential) + + with pytest.raises(ValueError): + client = SearchIndexClient(12345, credential) + + +class TestSearchIndexerClient: + def test_indexer_init(self): + client = SearchIndexerClient("endpoint", CREDENTIAL) + assert client._headers == { + "api-key": "test_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_indexer_credential_roll(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexerClient("endpoint", credential) + assert client._headers == { + "api-key": "old_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + credential.update("new_api_key") + assert client._headers == { + "api-key": "new_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_indexer_endpoint_https(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexerClient("endpoint", credential) + assert client._endpoint.startswith("https") + + client = SearchIndexerClient("https://endpoint", credential) + assert client._endpoint.startswith("https") + + with pytest.raises(ValueError): + client = SearchIndexerClient("http://endpoint", credential) + + with pytest.raises(ValueError): + client = SearchIndexerClient(12345, credential) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py new file mode 100644 index 000000000000..e5d15a396ff5 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_data_source_live_async.py @@ -0,0 +1,120 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator +from azure.search.documents.indexes.models import ( + SearchIndexerDataSourceConnection, + SearchIndexerDataContainer, +) +from azure.search.documents.indexes.aio import SearchIndexerClient + + +class TestSearchClientDataSourcesAsync(AzureRecordedTestCase): + def _create_data_source_connection(self, cs, name): + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name=name, type="azureblob", connection_string=cs, container=container + ) + return data_source_connection + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_data_source(self, endpoint, **kwargs): + storage_cs = kwargs.get("search_storage_connection_string") + client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + async with client: + await self._test_create_datasource(client, storage_cs) + await self._test_delete_datasource(client, storage_cs) + await self._test_get_datasource(client, storage_cs) + await self._test_list_datasources(client, storage_cs) + await self._test_create_or_update_datasource(client, storage_cs) + await self._test_create_or_update_datasource_if_unchanged(client, storage_cs) + await self._test_delete_datasource_if_unchanged(client, storage_cs) + + async def _test_create_datasource(self, client, storage_cs): + ds_name = "create" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + result = await client.create_data_source_connection(data_source_connection) + assert result.name == ds_name + assert result.type == "azureblob" + + async def _test_delete_datasource(self, client, storage_cs): + ds_name = "delete" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + await client.create_data_source_connection(data_source_connection) + expected_count = len(await client.get_data_source_connections()) - 1 + await client.delete_data_source_connection(ds_name) + assert len(await client.get_data_source_connections()) == expected_count + + async def _test_get_datasource(self, client, storage_cs): + ds_name = "get" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + await client.create_data_source_connection(data_source_connection) + result = await client.get_data_source_connection(ds_name) + assert result.name == ds_name + + async def _test_list_datasources(self, client, storage_cs): + data_source_connection1 = self._create_data_source_connection(storage_cs, "list") + data_source_connection2 = self._create_data_source_connection(storage_cs, "list2") + await client.create_data_source_connection(data_source_connection1) + await client.create_data_source_connection(data_source_connection2) + result = await client.get_data_source_connections() + assert isinstance(result, list) + assert set(x.name for x in result).intersection(set(["list", "list2"])) == set(["list", "list2"]) + + async def _test_create_or_update_datasource(self, client, storage_cs): + ds_name = "cou" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + await client.create_data_source_connection(data_source_connection) + expected_count = len(await client.get_data_source_connections()) + data_source_connection.description = "updated" + await client.create_or_update_data_source_connection(data_source_connection) + assert len(await client.get_data_source_connections()) == expected_count + result = await client.get_data_source_connection(ds_name) + assert result.name == ds_name + assert result.description == "updated" + + async def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): + ds_name = "couunch" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + created = await client.create_data_source_connection(data_source_connection) + etag = created.e_tag + + # Now update the data source connection + data_source_connection.description = "updated" + await client.create_or_update_data_source_connection(data_source_connection) + + # prepare data source connection + data_source_connection.e_tag = etag # reset to the original data source connection + data_source_connection.description = "changed" + with pytest.raises(HttpResponseError): + await client.create_or_update_data_source_connection( + data_source_connection, match_condition=MatchConditions.IfNotModified + ) + + async def _test_delete_datasource_if_unchanged(self, client, storage_cs): + ds_name = "delunch" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + created = await client.create_data_source_connection(data_source_connection) + etag = created.e_tag + + # Now update the data source connection + data_source_connection.description = "updated" + await client.create_or_update_data_source_connection(data_source_connection) + + # prepare data source connection + data_source_connection.e_tag = etag # reset to the original data source connection + with pytest.raises(HttpResponseError): + await client.delete_data_source_connection( + data_source_connection, match_condition=MatchConditions.IfNotModified + ) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py new file mode 100644 index 000000000000..8afea2e16425 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py @@ -0,0 +1,190 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import pytest + +from azure.core.exceptions import HttpResponseError +from azure.core import MatchConditions +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator +from azure.search.documents.indexes.aio import SearchIndexClient +from azure.search.documents.indexes.models import ( + AnalyzeTextOptions, + CorsOptions, + SearchIndex, + ScoringProfile, + SimpleField, + SearchFieldDataType, +) + + +class TestSearchIndexClientAsync(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema=None, index_batch=None) + @recorded_by_proxy_async + async def test_search_index_client(self, endpoint, index_name): + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + index_name = "hotels" + async with client: + await self._test_get_service_statistics(client) + await self._test_list_indexes_empty(client) + await self._test_create_index(client, index_name) + await self._test_list_indexes(client, index_name) + await self._test_get_index(client, index_name) + await self._test_get_index_statistics(client, index_name) + await self._test_delete_indexes_if_unchanged(client) + await self._test_create_or_update_index(client) + await self._test_create_or_update_indexes_if_unchanged(client) + await self._test_analyze_text(client, index_name) + await self._test_delete_indexes(client) + + async def _test_get_service_statistics(self, client): + result = await client.get_service_statistics() + assert isinstance(result, dict) + assert set(result.keys()) == {"counters", "limits"} + + async def _test_list_indexes_empty(self, client): + result = client.list_indexes() + with pytest.raises(StopAsyncIteration): + await result.__anext__() + + async def _test_create_index(self, client, index_name): + fields = fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=index_name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = await client.create_index(index) + assert result.name == "hotels" + assert result.scoring_profiles[0].name == scoring_profile.name + assert result.cors_options.allowed_origins == cors_options.allowed_origins + assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds + + async def _test_list_indexes(self, client, index_name): + result = client.list_indexes() + first = await result.__anext__() + assert first.name == index_name + with pytest.raises(StopAsyncIteration): + await result.__anext__() + + async def _test_get_index(self, client, index_name): + result = await client.get_index(index_name) + assert result.name == index_name + + async def _test_get_index_statistics(self, client, index_name): + result = await client.get_index_statistics(index_name) + keys = set(result.keys()) + assert "document_count" in keys + assert "storage_size" in keys + assert "vector_index_size" in keys + + async def _test_delete_indexes_if_unchanged(self, client): + # First create an index + name = "hotels-del-unchanged" + fields = [ + {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, + {"name": "baseRate", "type": "Edm.Double"}, + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = await client.create_index(index) + etag = result.e_tag + # get eTag and update + index.scoring_profiles = [] + await client.create_or_update_index(index) + + index.e_tag = etag + with pytest.raises(HttpResponseError): + await client.delete_index(index, match_condition=MatchConditions.IfNotModified) + + async def _test_create_or_update_index(self, client): + name = "hotels-cou" + fields = fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profiles = [] + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = await client.create_or_update_index(index=index) + assert len(result.scoring_profiles) == 0 + assert result.cors_options.allowed_origins == cors_options.allowed_origins + assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = await client.create_or_update_index(index=index) + assert result.scoring_profiles[0].name == scoring_profile.name + assert result.cors_options.allowed_origins == cors_options.allowed_origins + assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds + + async def _test_create_or_update_indexes_if_unchanged(self, client): + # First create an index + name = "hotels-coa-unchanged" + fields = [ + {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, + {"name": "baseRate", "type": "Edm.Double"}, + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = await client.create_index(index) + etag = result.e_tag + # get eTag and update + index.scoring_profiles = [] + await client.create_or_update_index(index) + + index.e_tag = etag + with pytest.raises(HttpResponseError): + await client.create_or_update_index(index, match_condition=MatchConditions.IfNotModified) + + async def _test_analyze_text(self, client, index_name): + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") + result = await client.analyze_text(index_name, analyze_request) + assert len(result.tokens) == 2 + + async def _test_delete_indexes(self, client): + result = client.list_indexes() + async for index in result: + await client.delete_index(index.name) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py new file mode 100644 index 000000000000..97308ba3ad33 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_skillset_live_async.py @@ -0,0 +1,217 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential +from search_service_preparer import SearchEnvVarPreparer, search_decorator +from azure.search.documents.indexes.models import ( + EntityLinkingSkill, + EntityRecognitionSkill, + EntityRecognitionSkillVersion, + InputFieldMappingEntry, + OutputFieldMappingEntry, + SearchIndexerSkillset, + SentimentSkill, + SentimentSkillVersion, +) +from azure.search.documents.indexes.aio import SearchIndexerClient + + +class TestSearchClientSkillsets(AzureRecordedTestCase): + @pytest.mark.skip("The skills are deprecated") + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_skillset_crud(self, endpoint): + client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + async with client: + await self._test_create_skillset(client) + await self._test_get_skillset(client) + await self._test_get_skillsets(client) + await self._test_create_or_update_skillset(client) + await self._test_create_or_update_skillset_if_unchanged(client) + await self._test_create_or_update_skillset_inplace(client) + await self._test_delete_skillset_if_unchanged(client) + await self._test_delete_skillset(client) + + async def _test_create_skillset(self, client): + name = "test-ss-create" + s1 = EntityRecognitionSkill( + name="skill1", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], + description="Skill Version 1", + model_version="1", + include_typeless_entities=True, + ) + + s2 = EntityRecognitionSkill( + name="skill2", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], + skill_version=EntityRecognitionSkillVersion.LATEST, + description="Skill Version 3", + model_version="3", + include_typeless_entities=True, + ) + s3 = SentimentSkill( + name="skill3", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], + skill_version=SentimentSkillVersion.V1, + description="Sentiment V1", + include_opinion_mining=True, + ) + + s4 = SentimentSkill( + name="skill4", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4")], + skill_version=SentimentSkillVersion.V3, + description="Sentiment V3", + include_opinion_mining=True, + ) + + s5 = EntityLinkingSkill( + name="skill5", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="entities", target_name="entitiesS5")], + minimum_precision=0.5, + ) + + skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s3, s4, s5]), description="desc") + result = await client.create_skillset(skillset) + + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc" + assert result.e_tag + assert len(result.skills) == 5 + assert isinstance(result.skills[0], EntityRecognitionSkill) + assert result.skills[0].skill_version == EntityRecognitionSkillVersion.V1 + assert isinstance(result.skills[1], EntityRecognitionSkill) + assert result.skills[1].skill_version == EntityRecognitionSkillVersion.V3 + assert isinstance(result.skills[2], SentimentSkill) + assert result.skills[2].skill_version == SentimentSkillVersion.V1 + assert isinstance(result.skills[3], SentimentSkill) + assert result.skills[3].skill_version == SentimentSkillVersion.V3 + assert isinstance(result.skills[4], EntityLinkingSkill) + assert result.skills[4].minimum_precision == 0.5 + + assert len(await client.get_skillsets()) == 1 + await client.reset_skills(result, [x.name for x in result.skills]) + + async def _test_get_skillset(self, client): + name = "test-ss-get" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") + await client.create_skillset(skillset) + result = await client.get_skillset(name) + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc" + assert result.e_tag + assert len(result.skills) == 1 + assert isinstance(result.skills[0], EntityRecognitionSkill) + + async def _test_get_skillsets(self, client): + name1 = "test-ss-list-1" + name2 = "test-ss-list-2" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name1, skills=list([s]), description="desc1") + await client.create_skillset(skillset1) + skillset2 = SearchIndexerSkillset(name=name2, skills=list([s]), description="desc2") + await client.create_skillset(skillset2) + result = await client.get_skillsets() + assert isinstance(result, list) + assert all(isinstance(x, SearchIndexerSkillset) for x in result) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) + + async def _test_create_or_update_skillset(self, client): + name = "test-ss-create-or-update" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") + await client.create_or_update_skillset(skillset1) + expected_count = len(await client.get_skillsets()) + skillset2 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc2") + await client.create_or_update_skillset(skillset2) + assert len(await client.get_skillsets()) == expected_count + + result = await client.get_skillset(name) + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc2" + + async def _test_create_or_update_skillset_inplace(self, client): + name = "test-ss-create-or-update-inplace" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") + ss = await client.create_or_update_skillset(skillset1) + expected_count = len(await client.get_skillsets()) + skillset2 = SearchIndexerSkillset(name=name, skills=[s], description="desc2", skillset=ss) + await client.create_or_update_skillset(skillset2) + assert len(await client.get_skillsets()) == expected_count + + result = await client.get_skillset(name) + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc2" + + async def _test_create_or_update_skillset_if_unchanged(self, client): + name = "test-ss-create-or-update-unchanged" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") + ss = await client.create_or_update_skillset(skillset1) + + ss.e_tag = "changed_etag" + + with pytest.raises(HttpResponseError): + await client.create_or_update_skillset(ss, match_condition=MatchConditions.IfNotModified) + + async def _test_delete_skillset_if_unchanged(self, client): + name = "test-ss-deleted-unchanged" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") + result = await client.create_skillset(skillset) + etag = result.e_tag + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="updated") + updated = await client.create_or_update_skillset(skillset1) + updated.e_tag = etag + + with pytest.raises(HttpResponseError): + await client.delete_skillset(updated, match_condition=MatchConditions.IfNotModified) + + async def _test_delete_skillset(self, client): + result = await client.get_skillset_names() + for skillset in result: + await client.delete_skillset(skillset) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py new file mode 100644 index 000000000000..41a92e92f91c --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_synonym_map_live_async.py @@ -0,0 +1,147 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest + +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes.aio import SearchIndexClient +from azure.search.documents.indexes.models import SynonymMap +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils import AzureRecordedTestCase, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClientSynonymMaps(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_synonym_map(self, endpoint): + client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + async with client: + await self._test_create_synonym_map(client) + await self._test_delete_synonym_map(client) + await self._test_delete_synonym_map_if_unchanged(client) + await self._test_get_synonym_map(client) + await self._test_get_synonym_maps(client) + await self._test_create_or_update_synonym_map(client) + + async def _test_create_synonym_map(self, client): + expected = len(await client.get_synonym_maps()) + 1 + name = "synmap-create" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + result = await client.create_synonym_map(synonym_map) + assert isinstance(result, SynonymMap) + assert result.name == name + assert result.synonyms == [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + assert len(await client.get_synonym_maps()) == expected + await client.delete_synonym_map(name) + + async def _test_delete_synonym_map(self, client): + name = "synmap-del" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + result = await client.create_synonym_map(synonym_map) + expected = len(await client.get_synonym_maps()) - 1 + await client.delete_synonym_map(name) + assert len(await client.get_synonym_maps()) == expected + + async def _test_delete_synonym_map_if_unchanged(self, client): + name = "synmap-delunch" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + result = await client.create_synonym_map(synonym_map) + etag = result.e_tag + + synonym_map.synonyms = "\n".join( + [ + "Washington, Wash. => WA", + ] + ) + await client.create_or_update_synonym_map(synonym_map) + + result.e_tag = etag + with pytest.raises(HttpResponseError): + await client.delete_synonym_map(result, match_condition=MatchConditions.IfNotModified) + await client.delete_synonym_map(name) + + async def _test_get_synonym_map(self, client): + expected = len(await client.get_synonym_maps()) + 1 + name = "synmap-get" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + await client.create_synonym_map(synonym_map) + assert len(await client.get_synonym_maps()) == expected + result = await client.get_synonym_map(name) + assert isinstance(result, SynonymMap) + assert result.name == name + assert result.synonyms == [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + await client.delete_synonym_map(name) + + async def _test_get_synonym_maps(self, client): + name1 = "synmap-list1" + name2 = "synmap-list2" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map_1 = SynonymMap(name=name1, synonyms=synonyms) + await client.create_synonym_map(synonym_map_1) + synonyms = [ + "Washington, Wash. => WA", + ] + synonym_map_2 = SynonymMap(name=name2, synonyms=synonyms) + await client.create_synonym_map(synonym_map_2) + result = await client.get_synonym_maps() + assert isinstance(result, list) + assert all(isinstance(x, SynonymMap) for x in result) + expected = set([name1, name2]) + assert set(x.name for x in result).intersection(expected) == expected + await client.delete_synonym_map(name1) + await client.delete_synonym_map(name2) + + async def _test_create_or_update_synonym_map(self, client): + expected = len(await client.get_synonym_maps()) + 1 + name = "synmap-cou" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + await client.create_synonym_map(synonym_map) + assert len(await client.get_synonym_maps()) == expected + synonym_map.synonyms = [ + "Washington, Wash. => WA", + ] + await client.create_or_update_synonym_map(synonym_map) + assert len(await client.get_synonym_maps()) == expected + result = await client.get_synonym_map(name) + assert isinstance(result, SynonymMap) + assert result.name == name + assert result.synonyms == [ + "Washington, Wash. => WA", + ] + await client.delete_synonym_map(name) diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py new file mode 100644 index 000000000000..31cc3aa6f6a5 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_indexer_client_live_async.py @@ -0,0 +1,154 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes.aio import SearchIndexClient, SearchIndexerClient +from azure.search.documents.indexes.models import ( + SearchIndex, + SearchIndexer, + SearchIndexerDataContainer, + SearchIndexerDataSourceConnection, +) +from devtools_testutils import AzureRecordedTestCase, get_credential +from devtools_testutils.aio import recorded_by_proxy_async + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchIndexerClientTestAsync(AzureRecordedTestCase): + @pytest.mark.skip("fails because connection string of storage is disabled") + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy_async + async def test_search_indexers(self, endpoint, **kwargs): + storage_cs = kwargs.get("search_storage_connection_string") + container_name = kwargs.get("search_storage_container_name") + client = SearchIndexerClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + index_client = SearchIndexClient(endpoint, get_credential(is_async=True), retry_backoff_factor=60) + async with client: + async with index_client: + await self._test_create_indexer(client, index_client, storage_cs, container_name) + await self._test_delete_indexer(client, index_client, storage_cs, container_name) + await self._test_get_indexer(client, index_client, storage_cs, container_name) + await self._test_list_indexer(client, index_client, storage_cs, container_name) + await self._test_create_or_update_indexer(client, index_client, storage_cs, container_name) + await self._test_reset_indexer(client, index_client, storage_cs, container_name) + await self._test_run_indexer(client, index_client, storage_cs, container_name) + await self._test_get_indexer_status(client, index_client, storage_cs, container_name) + await self._test_create_or_update_indexer_if_unchanged(client, index_client, storage_cs, container_name) + await self._test_delete_indexer_if_unchanged(client, index_client, storage_cs, container_name) + + async def _prepare_indexer(self, client, index_client, storage_cs, name, container_name): + data_source_connection = SearchIndexerDataSourceConnection( + name=f"{name}-ds", + type="azureblob", + connection_string=storage_cs, + container=SearchIndexerDataContainer(name=container_name), + ) + ds = await client.create_data_source_connection(data_source_connection) + + fields = [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}] + index = SearchIndex(name=f"{name}-hotels", fields=fields) + ind = await index_client.create_index(index) + return SearchIndexer(name=name, data_source_name=ds.name, target_index_name=ind.name) + + async def _test_create_indexer(self, client, index_client, storage_cs, container_name): + name = "create" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + result = await client.create_indexer(indexer) + assert result.name == name + assert result.target_index_name == f"{name}-hotels" + assert result.data_source_name == f"{name}-ds" + + async def _test_delete_indexer(self, client, index_client, storage_cs, container_name): + name = "delete" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + await client.create_indexer(indexer) + expected = len(await client.get_indexers()) - 1 + await client.delete_indexer(name) + assert len(await client.get_indexers()) == expected + + async def _test_get_indexer(self, client, index_client, storage_cs, container_name): + name = "get" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + await client.create_indexer(indexer) + result = await client.get_indexer(name) + assert result.name == name + + async def _test_list_indexer(self, client, index_client, storage_cs, container_name): + name1 = "list1" + name2 = "list2" + indexer1 = await self._prepare_indexer(client, index_client, storage_cs, name1, container_name) + indexer2 = await self._prepare_indexer(client, index_client, storage_cs, name2, container_name) + await client.create_indexer(indexer1) + await client.create_indexer(indexer2) + result = await client.get_indexers() + assert isinstance(result, list) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) + + async def _test_create_or_update_indexer(self, client, index_client, storage_cs, container_name): + name = "cou" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + await client.create_indexer(indexer) + expected = len(await client.get_indexers()) + indexer.description = "updated" + await client.create_or_update_indexer(indexer) + assert len(await client.get_indexers()) == expected + result = await client.get_indexer(name) + assert result.name == name + assert result.description == "updated" + + async def _test_reset_indexer(self, client, index_client, storage_cs, container_name): + name = "reset" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + await client.create_indexer(indexer) + await client.reset_indexer(name) + assert (await client.get_indexer_status(name)).last_result.status.lower() in ( + "inprogress", + "reset", + ) + + async def _test_run_indexer(self, client, index_client, storage_cs, container_name): + name = "run" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + await client.create_indexer(indexer) + await client.run_indexer(name) + assert (await client.get_indexer_status(name)).status == "running" + + async def _test_get_indexer_status(self, client, index_client, storage_cs, container_name): + name = "get-status" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + await client.create_indexer(indexer) + status = await client.get_indexer_status(name) + assert status.status is not None + + async def _test_create_or_update_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): + name = "couunch" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + created = await client.create_indexer(indexer) + etag = created.e_tag + + indexer.description = "updated" + await client.create_or_update_indexer(indexer) + + indexer.e_tag = etag + with pytest.raises(HttpResponseError): + await client.create_or_update_indexer(indexer, match_condition=MatchConditions.IfNotModified) + + async def _test_delete_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): + name = "delunch" + indexer = await self._prepare_indexer(client, index_client, storage_cs, name, container_name) + result = await client.create_indexer(indexer) + etag = result.e_tag + + indexer.description = "updated" + await client.create_or_update_indexer(indexer) + + indexer.e_tag = etag + with pytest.raises(HttpResponseError): + await client.delete_indexer(indexer, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/conftest.py b/sdk/search/azure-search-documents/tests/conftest.py new file mode 100644 index 000000000000..0ecac854421a --- /dev/null +++ b/sdk/search/azure-search-documents/tests/conftest.py @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ------------------------------------------------------------------------- + +import sys +import pytest +from devtools_testutils import test_proxy, remove_batch_sanitizers +from devtools_testutils.sanitizers import ( + add_remove_header_sanitizer, + add_general_regex_sanitizer, +) + +# Ignore async tests for Python < 3.5 +collect_ignore = [] +if sys.version_info < (3, 5): + collect_ignore.append("async_tests") + + +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + add_remove_header_sanitizer(headers="api-key") + + # Ensure all search service endpoint names are mocked to "test-service" + add_general_regex_sanitizer( + value="://fakesearchendpoint.search.windows.net", + regex=r"://(.+).search.windows.net", + ) + # Remove storage connection strings from recordings + add_general_regex_sanitizer(value="AccountKey=FAKE;", regex=r"AccountKey=([^;]+);") + # Remove storage account names from recordings + add_general_regex_sanitizer(value="AccountName=fakestoragecs;", regex=r"AccountName=([^;]+);") + # Remove the following sanitizers since certain fields are needed in tests and are non-sensitive: + # - AZSDK3493: $..name + remove_batch_sanitizers(["AZSDK3493"]) diff --git a/sdk/search/azure-search-documents/tests/hotel_large.json b/sdk/search/azure-search-documents/tests/hotel_large.json new file mode 100644 index 000000000000..10f286f65c0d --- /dev/null +++ b/sdk/search/azure-search-documents/tests/hotel_large.json @@ -0,0 +1,1504 @@ +{ + "value": [ + { + "@search.action": "upload", + "hotelId": "1", + "hotelName": "Fancy Stay", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "2", + "hotelName": "Roach Motel", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "3", + "hotelName": "EconoStay", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "4", + "hotelName": "Express Rooms", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "5", + "hotelName": "Comfy Place", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "6", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "7", + "hotelName": "Modern Stay", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "8", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "9", + "hotelName": "Secret Point Motel", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "10", + "hotelName": "Countryside Hotel", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "11", + "hotelName": "Fancy Stay 1", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "12", + "hotelName": "Roach Motel 1", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "13", + "hotelName": "EconoStay 1", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "14", + "hotelName": "Express Rooms 1", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "15", + "hotelName": "Comfy Place 1", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "16", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "17", + "hotelName": "Modern Stay1", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "18", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "19", + "hotelName": "Secret Point Motel 1", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "20", + "hotelName": "Countryside Hotel 1", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "21", + "hotelName": "Fancy Stay 2", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "22", + "hotelName": "Roach Motel2", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "23", + "hotelName": "EconoStay2", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "24", + "hotelName": "Express Rooms2", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "25", + "hotelName": "Comfy Place2", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "26", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "27", + "hotelName": "Modern Stay2", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "28", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "29", + "hotelName": "Secret Point Motel2", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "30", + "hotelName": "Countryside Hotel 2", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "31", + "hotelName": "Fancy Stay3", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "32", + "hotelName": "Roach Motel3", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "33", + "hotelName": "EconoStay3", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "34", + "hotelName": "Express Rooms3", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "35", + "hotelName": "Comfy Place3", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "36", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "37", + "hotelName": "Modern Stay3", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "38", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "39", + "hotelName": "Secret Point Motel3", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "40", + "hotelName": "Countryside Hotel", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "41", + "hotelName": "Fancy Stay4", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "42", + "hotelName": "Roach Motel4", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "43", + "hotelName": "EconoStay4", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "44", + "hotelName": "Express Rooms4", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "45", + "hotelName": "Comfy Place4", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "46", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "47", + "hotelName": "Modern Stay4", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "48", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "49", + "hotelName": "Secret Point Motel4", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "50", + "hotelName": "Countryside Hotel", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "51", + "hotelName": "Fancy Stay5", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "52", + "hotelName": "Roach Motel5", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "53", + "hotelName": "EconoStay5", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "54", + "hotelName": "Express Rooms5", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "55", + "hotelName": "Comfy Place5", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "56", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "57", + "hotelName": "Modern Stay5", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "58", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "59", + "hotelName": "Secret Point Motel5", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "60", + "hotelName": "Countryside Hotel 5", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + } + ] + } \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/hotel_schema.json b/sdk/search/azure-search-documents/tests/hotel_schema.json new file mode 100644 index 000000000000..606379345d48 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/hotel_schema.json @@ -0,0 +1,288 @@ +{ + "name": "drgqefsg", + "fields": [ + { + "name": "hotelId", + "type": "Edm.String", + "key": true, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "hotelName", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": true, + "facetable": false + }, + { + "name": "description", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": false, + "sortable": false, + "facetable": false, + "analyzer": "en.lucene" + }, + { + "name": "descriptionFr", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": false, + "sortable": false, + "facetable": false, + "analyzer": "fr.lucene" + }, + { + "name": "category", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "tags", + "type": "Collection(Edm.String)", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": false, + "facetable": true + }, + { + "name": "parkingIncluded", + "type": "Edm.Boolean", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "smokingAllowed", + "type": "Edm.Boolean", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "lastRenovationDate", + "type": "Edm.DateTimeOffset", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "rating", + "type": "Edm.Int32", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "location", + "type": "Edm.GeographyPoint", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": true, + "facetable": false + }, + { + "name": "address", + "type": "Edm.ComplexType", + "fields": [ + { + "name": "streetAddress", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": false, + "sortable": false, + "facetable": false + }, + { + "name": "city", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "stateProvince", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "country", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": true, + "facetable": true + }, + { + "name": "postalCode", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": true, + "facetable": true + } + ] + }, + { + "name": "rooms", + "type": "Collection(Edm.ComplexType)", + "fields": [ + { + "name": "description", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": false, + "sortable": false, + "facetable": false, + "analyzer": "en.lucene" + }, + { + "name": "descriptionFr", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": false, + "sortable": false, + "facetable": false, + "analyzer": "fr.lucene" + }, + { + "name": "type", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": false, + "facetable": true + }, + { + "name": "baseRate", + "type": "Edm.Double", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": false, + "facetable": true + }, + { + "name": "bedOptions", + "type": "Edm.String", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": false, + "facetable": true + }, + { + "name": "sleepsCount", + "type": "Edm.Int32", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": false, + "facetable": true + }, + { + "name": "smokingAllowed", + "type": "Edm.Boolean", + "key": false, + "retrievable": true, + "searchable": false, + "filterable": true, + "sortable": false, + "facetable": true + }, + { + "name": "tags", + "type": "Collection(Edm.String)", + "key": false, + "retrievable": true, + "searchable": true, + "filterable": true, + "sortable": false, + "facetable": true + } + ] + } + ], + "scoringProfiles": [ + { + "name": "nearest", + "functions": [ + { + "type": "distance", + "distance": { + "referencePointParameter": "myloc", + "boostingDistance": 100.0 + }, + "fieldName": "location", + "boost": 2.0 + } + ], + "functionAggregation": "sum" + } + ], + "suggesters": [ + { + "name": "sg", + "sourceFields": [ + "description", + "hotelName" + ], + "searchMode": "analyzingInfixMatching" + } + ] +} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/hotel_small.json b/sdk/search/azure-search-documents/tests/hotel_small.json new file mode 100644 index 000000000000..6ea1027a61e3 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/hotel_small.json @@ -0,0 +1,254 @@ +{ + "value": [ + { + "@search.action": "upload", + "hotelId": "1", + "hotelName": "Fancy Stay", + "description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", + "descriptionFr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", + "category": "Luxury", + "tags": [ + "pool", + "view", + "wifi", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": false, + "lastRenovationDate": "2010-06-27T00:00:00+00:00", + "rating": 5, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 47.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "2", + "hotelName": "Roach Motel", + "description": "Cheapest hotel in town. Infact, a motel.", + "descriptionFr": "Hôtel le moins cher en ville. Infact, un motel.", + "category": "Budget", + "tags": [ + "motel", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": true, + "lastRenovationDate": "1982-04-28T00:00:00+00:00", + "rating": 1, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 49.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "3", + "hotelName": "EconoStay", + "description": "Very popular hotel in town", + "descriptionFr": "Hôtel le plus populaire en ville", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 46.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "4", + "hotelName": "Express Rooms", + "description": "Pretty good hotel", + "descriptionFr": "Assez bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "1995-07-01T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "5", + "hotelName": "Comfy Place", + "description": "Another good hotel", + "descriptionFr": "Un autre bon hôtel", + "category": "Budget", + "tags": [ + "wifi", + "budget" + ], + "parkingIncluded": true, + "smokingAllowed": false, + "lastRenovationDate": "2012-08-12T00:00:00+00:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -122.131577, + 48.678581 + ] + } + }, + { + "@search.action": "upload", + "hotelId": "6", + "description": "Surprisingly expensive. Model suites have an ocean-view." + }, + { + "@search.action": "upload", + "hotelId": "7", + "hotelName": "Modern Stay", + "description": "Modern architecture, very polite staff and very clean. Also very affordable.", + "descriptionFr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." + }, + { + "@search.action": "upload", + "hotelId": "8", + "description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", + "descriptionFr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." + }, + { + "@search.action": "upload", + "hotelId": "9", + "hotelName": "Secret Point Motel", + "description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", + "descriptionFr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", + "category": "Boutique", + "tags": [ + "pool", + "air conditioning", + "concierge" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1970-01-18T00:00:00-05:00", + "rating": 4, + "location": { + "type": "Point", + "coordinates": [ + -73.975403, + 40.760586 + ] + }, + "address": { + "streetAddress": "677 5th Ave", + "city": "New York", + "stateProvince": "NY", + "country": "USA", + "postalCode": "10022" + }, + "rooms": [ + { + "description": "Budget Room, 1 Queen Bed (Cityside)", + "descriptionFr": "Chambre Économique, 1 grand lit (côté ville)", + "type": "Budget Room", + "baseRate": 9.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd" + ] + }, + { + "description": "Budget Room, 1 King Bed (Mountain View)", + "descriptionFr": "Chambre Économique, 1 très grand lit (Mountain View)", + "type": "Budget Room", + "baseRate": 8.09, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "vcr/dvd", + "jacuzzi tub" + ] + } + ] + }, + { + "@search.action": "upload", + "hotelId": "10", + "hotelName": "Countryside Hotel", + "description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.", + "descriptionFr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.", + "category": "Budget", + "tags": [ + "24-hour front desk service", + "coffee in lobby", + "restaurant" + ], + "parkingIncluded": false, + "smokingAllowed": true, + "lastRenovationDate": "1999-09-06T00:00:00+00:00", + "rating": 3, + "location": { + "type": "Point", + "coordinates": [ + -78.940483, + 35.90416 + ] + }, + "address": { + "streetAddress": "6910 Fayetteville Rd", + "city": "Durham", + "stateProvince": "NC", + "country": "USA", + "postalCode": "27713" + }, + "rooms": [ + { + "description": "Suite, 1 King Bed (Amenities)", + "descriptionFr": "Suite, 1 très grand lit (Services)", + "type": "Suite", + "baseRate": 2.44, + "bedOptions": "1 King Bed", + "sleepsCount": 2, + "smokingAllowed": true, + "tags": [ + "coffee maker" + ] + }, + { + "description": "Budget Room, 1 Queen Bed (Amenities)", + "descriptionFr": "Chambre Économique, 1 grand lit (Services)", + "type": "Budget Room", + "baseRate": 7.69, + "bedOptions": "1 Queen Bed", + "sleepsCount": 2, + "smokingAllowed": false, + "tags": [ + "coffee maker" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/README.md b/sdk/search/azure-search-documents/tests/perfstress_tests/README.md new file mode 100644 index 000000000000..164216faf843 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/README.md @@ -0,0 +1,47 @@ +# Search Performance Tests + +In order to run the performance tests, the `devtools_testutils` package must be installed. This is done as part of the `dev_requirements`. +Start be creating a new virtual environment for your perf tests. This will need to be a Python 3 environment, preferably >=3.8. + +### Setup for test resources + +These tests will run against a pre-configured search service. See [here](https://learn.microsoft.com/azure/search/search-indexer-tutorial) about how to configure the service and import data. The following environment variable will need to be set for the tests to access the live resources: +``` +AZURE_SEARCH_API_KEY= +AZURE_SEARCH_SERVICE_ENDPOINT= +AZURE_SEARCH_INDEX_NAME= +``` + +### Setup for perf test runs + +```cmd +(env) ~/search/azure-search-documents> pip install -r dev_requirements.txt +(env) ~/search/azure-search-documents> pip install -e . +``` + +## Test commands + +When `devtools_testutils` is installed, you will have access to the `perfstress` command line tool, which will scan the current module for runable perf tests. Only a specific test can be run at a time (i.e. there is no "run all" feature). + +```cmd +(env) ~/search/azure-search-documents> cd tests +(env) ~/search/azure-search-documents/tests> perfstress +``` +Using the `perfstress` command alone will list the available perf tests found. + +### Common perf command line options +These options are available for all perf tests: +- `--duration=10` Number of seconds to run as many operations (the "run" function) as possible. Default is 10. +- `--iterations=1` Number of test iterations to run. Default is 1. +- `--parallel=1` Number of tests to run in parallel. Default is 1. +- `--warm-up=5` Number of seconds to spend warming up the connection before measuring begins. Default is 5. +- `--sync` Whether to run the tests in sync or async. Default is False (async). This flag must be used for Storage legacy tests, which do not support async. +- `--no-cleanup` Whether to keep newly created resources after test run. Default is False (resources will be deleted). +- `--num-documents` The number of results expect to be returned. + +## Example command +```cmd +(env) ~/search/azure-search-documents/tests> perfstress SearchDocumentsTest +(env) ~/search/azure-search-documents/tests> perfstress AutoCompleteTest +(env) ~/search/azure-search-documents/tests> perfstress SuggestTest +``` diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/__init__.py b/sdk/search/azure-search-documents/tests/perfstress_tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py b/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py new file mode 100644 index 000000000000..ccd2a6a595f6 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/autocomplete.py @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os +from devtools_testutils.perfstress_tests import PerfStressTest + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchClient as SyncClient +from azure.search.documents.aio import SearchClient as AsyncClient + + +class AutoCompleteTest(PerfStressTest): + def __init__(self, arguments): + super().__init__(arguments) + api_key = self.get_from_env("AZURE_SEARCH_API_KEY") + service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") + index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") + key = os.getenv("AZURE_SEARCH_API_KEY") + self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + + async def close(self): + await self.async_service_client.close() + await super().close() + + @staticmethod + def add_arguments(parser): + super(AutoCompleteTest, AutoCompleteTest).add_arguments(parser) + parser.add_argument( + "--num-documents", + nargs="?", + type=int, + help="The number of results expect to be returned.", + default=-1, + ) + + def run_sync(self): + if self.args.num_documents == -1: + results = len(self.service_client.autocomplete(search_text="mot", suggester_name="sg")) + else: + results = len( + self.service_client.autocomplete(search_text="mot", suggester_name="sg", top=self.args.num_documents) + ) + + async def run_async(self): + if self.args.num_documents == -1: + results = len(await self.async_service_client.autocomplete(search_text="mot", suggester_name="sg")) + else: + results = len( + await self.async_service_client.autocomplete( + search_text="mot", suggester_name="sg", top=self.args.num_documents + ) + ) diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py b/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py new file mode 100644 index 000000000000..19fc00efec37 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/search_documents.py @@ -0,0 +1,56 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os + +from devtools_testutils.perfstress_tests import PerfStressTest + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchClient as SyncClient +from azure.search.documents.aio import SearchClient as AsyncClient + + +class SearchDocumentsTest(PerfStressTest): + def __init__(self, arguments): + super().__init__(arguments) + api_key = self.get_from_env("AZURE_SEARCH_API_KEY") + service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") + index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") + key = os.getenv("AZURE_SEARCH_API_KEY") + self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + + @staticmethod + def add_arguments(parser): + super(SearchDocumentsTest, SearchDocumentsTest).add_arguments(parser) + parser.add_argument( + "--num-documents", + nargs="?", + type=int, + help="The number of results expect to be returned.", + default=-1, + ) + + async def global_setup(self): + await super().global_setup() + + async def close(self): + await self.async_service_client.close() + await super().close() + + def run_sync(self): + if self.args.num_documents == -1: + results = len(self.service_client.search(search_text="luxury")) + else: + results = len(self.service_client.search(search_text="luxury", top=self.args.num_documents)) + + async def run_async(self): + if self.args.num_documents == -1: + results = await self.async_service_client.search(search_text="luxury") + else: + results = await self.async_service_client.search(search_text="luxury", top=self.args.num_documents) + count = 0 + async for result in results: + count += count diff --git a/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py b/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py new file mode 100644 index 000000000000..d906ba271ef8 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/perfstress_tests/suggest.py @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os +from devtools_testutils.perfstress_tests import PerfStressTest + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchClient as SyncClient +from azure.search.documents.aio import SearchClient as AsyncClient + + +class SuggestTest(PerfStressTest): + def __init__(self, arguments): + super().__init__(arguments) + api_key = self.get_from_env("AZURE_SEARCH_API_KEY") + service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") + index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") + key = os.getenv("AZURE_SEARCH_API_KEY") + self.service_client = SyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + self.async_service_client = AsyncClient(service_endpoint, index_name, AzureKeyCredential(api_key)) + + async def close(self): + await self.async_service_client.close() + await super().close() + + @staticmethod + def add_arguments(parser): + super(SuggestTest, SuggestTest).add_arguments(parser) + parser.add_argument( + "--num-documents", + nargs="?", + type=int, + help="The number of results expect to be returned.", + default=-1, + ) + + def run_sync(self): + if self.args.num_documents == -1: + results = len(self.service_client.suggest(search_text="mot", suggester_name="sg")) + else: + results = len( + self.service_client.suggest(search_text="mot", suggester_name="sg", top=self.args.num_documents) + ) + + async def run_async(self): + if self.args.num_documents == -1: + results = len(await self.async_service_client.suggest(search_text="mot", suggester_name="sg")) + else: + results = len( + await self.async_service_client.suggest( + search_text="mot", suggester_name="sg", top=self.args.num_documents + ) + ) diff --git a/sdk/search/azure-search-documents/tests/search_service_preparer.py b/sdk/search/azure-search-documents/tests/search_service_preparer.py new file mode 100644 index 000000000000..d4de15e3b660 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/search_service_preparer.py @@ -0,0 +1,158 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import functools +from os import environ +from os.path import dirname, realpath, join + +import inspect +import json +import requests + +from devtools_testutils import AzureTestError, EnvironmentVariableLoader, get_credential + +from azure.core.exceptions import HttpResponseError + +SERVICE_URL_FMT = "https://{}.{}/indexes?api-version=2023-11-01" +TIME_TO_SLEEP = 3 +SEARCH_ENDPOINT_SUFFIX = environ.get("SEARCH_ENDPOINT_SUFFIX", "search.windows.net") + +SearchEnvVarPreparer = functools.partial( + EnvironmentVariableLoader, + "search", + search_service_endpoint="https://fakesearchendpoint.search.windows.net", + search_service_name="fakesearchendpoint", + search_storage_connection_string="DefaultEndpointsProtocol=https;AccountName=fakestoragecs;AccountKey=FAKE;EndpointSuffix=core.windows.net", + search_storage_container_name="fakestoragecontainer", +) + + +def _load_schema(filename): + if not filename: + return None + cwd = dirname(realpath(__file__)) + return open(join(cwd, filename)).read() + + +def _load_batch(filename): + if not filename: + return None + cwd = dirname(realpath(__file__)) + try: + return json.load(open(join(cwd, filename))) + except UnicodeDecodeError: + return json.load(open(join(cwd, filename), encoding="utf-8")) + + +def _clean_up_indexes(endpoint, cred): + from azure.search.documents.indexes import SearchIndexClient + + client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) + + # wipe the synonym maps which seem to survive the index + for map in client.get_synonym_maps(): + client.delete_synonym_map(map.name) + # wipe out any existing aliases + for alias in client.list_aliases(): + client.delete_alias(alias) + + # wipe any existing indexes + for index in client.list_indexes(): + client.delete_index(index) + + +def _clean_up_indexers(endpoint, cred): + from azure.search.documents.indexes import SearchIndexerClient + + client = SearchIndexerClient(endpoint, cred, retry_backoff_factor=60) + for indexer in client.get_indexers(): + client.delete_indexer(indexer) + for datasource in client.get_data_source_connection_names(): + client.delete_data_source_connection(datasource) + try: + for skillset in client.get_skillset_names(): + client.delete_skillset(skillset) + except HttpResponseError as ex: + if "skillset related operations are not enabled in this region" in ex.message.lower(): + pass + else: + raise + + +def _set_up_index(service_name, endpoint, cred, schema, index_batch): + from azure.search.documents import SearchClient + from azure.search.documents.indexes.models import SearchIndex + from azure.search.documents._generated.models import IndexBatch + from azure.search.documents.indexes import SearchIndexClient + + schema = _load_schema(schema) + index_batch = _load_batch(index_batch) + if schema: + index_json = json.loads(schema) + index_name = index_json["name"] + index = SearchIndex.from_dict(index_json) + index_client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) + index_create = index_client.create_index(index) + + # optionally load data into the index + if index_batch and schema: + batch = IndexBatch.deserialize(index_batch) + client = SearchClient(endpoint, index_name, cred) + results = client.index_documents(batch) + if not all(result.succeeded for result in results): + raise AzureTestError("Document upload to search index failed") + + # Indexing is asynchronous, so if you get a 200 from the REST API, that only means that the documents are + # persisted, not that they're searchable yet. The only way to check for searchability is to run queries, + # and even then things are eventually consistent due to replication. In the Track 1 SDK tests, we "solved" + # this by using a constant delay between indexing and querying. + import time + + time.sleep(TIME_TO_SLEEP) + + +def _trim_kwargs_from_test_function(fn, kwargs): + # the next function is the actual test function. the kwargs need to be trimmed so + # that parameters which are not required will not be passed to it. + if not getattr(fn, "__is_preparer", False): + try: + args, _, kw, _, _, _, _ = inspect.getfullargspec(fn) + except AttributeError: + args, _, kw, _ = inspect.getargspec(fn) # pylint: disable=deprecated-method + if kw is None: + args = set(args) + for key in [k for k in kwargs if k not in args]: + del kwargs[key] + + +def search_decorator(*, schema, index_batch): + def decorator(func): + def wrapper(*args, **kwargs): + # set up hotels search index + test = args[0] + endpoint = kwargs.get("search_service_endpoint") + service_name = kwargs.get("search_service_name") + if test.is_live: + cred = get_credential() + _clean_up_indexes(endpoint, cred) + _set_up_index(service_name, endpoint, cred, schema, index_batch) + _clean_up_indexers(endpoint, cred) + index_name = json.loads(_load_schema(schema))["name"] if schema else None + index_batch_data = _load_batch(index_batch) if index_batch else None + + # ensure that the names in the test signatures are in the + # bag of kwargs + kwargs["endpoint"] = endpoint + kwargs["index_name"] = index_name + kwargs["index_batch"] = index_batch_data + + trimmed_kwargs = {k: v for k, v in kwargs.items()} + _trim_kwargs_from_test_function(func, trimmed_kwargs) + + return func(*args, **trimmed_kwargs) + + return wrapper + + return decorator diff --git a/sdk/search/azure-search-documents/tests/test_buffered_sender.py b/sdk/search/azure-search-documents/tests/test_buffered_sender.py new file mode 100644 index 000000000000..5af0b3d5efbf --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_buffered_sender.py @@ -0,0 +1,154 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from unittest import mock +import pytest +from azure.search.documents import ( + SearchIndexingBufferedSender, +) +from azure.core.credentials import AzureKeyCredential +from azure.core.exceptions import HttpResponseError, ServiceResponseTimeoutError +from azure.search.documents.models import IndexingResult + +CREDENTIAL = AzureKeyCredential(key="test_api_key") + + +class TestSearchBatchingClient: + def test_search_indexing_buffered_sender_kwargs(self): + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, window=100) as client: + assert client._batch_action_count == 512 + assert client._max_retries_per_action == 3 + assert client._auto_flush_interval == 60 + assert client._auto_flush + + def test_batch_queue(self): + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + assert client._index_documents_batch + client.upload_documents(["upload1"]) + client.delete_documents(["delete1", "delete2"]) + client.merge_documents(["merge1", "merge2", "merge3"]) + client.merge_or_upload_documents(["merge_or_upload1"]) + assert len(client.actions) == 7 + actions = client._index_documents_batch.dequeue_actions() + assert len(client.actions) == 0 + client._index_documents_batch.enqueue_actions(actions) + assert len(client.actions) == 7 + actions = client._index_documents_batch.dequeue_actions() + assert len(client.actions) == 0 + for action in actions: + client._index_documents_batch.enqueue_actions(action) + assert len(client.actions) == 7 + + @mock.patch( + "azure.search.documents._search_indexing_buffered_sender.SearchIndexingBufferedSender._process_if_needed" + ) + def test_process_if_needed(self, mock_process_if_needed): + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL) as client: + client.upload_documents(["upload1"]) + client.delete_documents(["delete1", "delete2"]) + assert mock_process_if_needed.called + + @mock.patch("azure.search.documents._search_indexing_buffered_sender.SearchIndexingBufferedSender._cleanup") + def test_context_manager(self, mock_cleanup): + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + client.upload_documents(["upload1"]) + client.delete_documents(["delete1", "delete2"]) + assert mock_cleanup.called + + def test_flush(self): + DOCUMENT = { + "category": "Hotel", + "hotelId": "1000", + "rating": 4.0, + "rooms": [], + "hotelName": "Azure Inn", + } + with mock.patch.object( + SearchIndexingBufferedSender, + "_index_documents_actions", + side_effect=HttpResponseError("Error"), + ): + with SearchIndexingBufferedSender("endpoint", "index name", CREDENTIAL, auto_flush=False) as client: + client._index_key = "hotelId" + client.upload_documents([DOCUMENT]) + client.flush() + assert len(client.actions) == 0 + + def test_callback_new(self): + on_new = mock.Mock() + with SearchIndexingBufferedSender( + "endpoint", "index name", CREDENTIAL, auto_flush=False, on_new=on_new + ) as client: + client.upload_documents(["upload1"]) + assert on_new.called + + def test_callback_error(self): + def mock_fail_index_documents(actions, timeout=86400): + if len(actions) > 0: + result = IndexingResult() + result.key = actions[0].additional_properties.get("id") + result.status_code = 400 + result.succeeded = False + self.uploaded = self.uploaded + len(actions) - 1 + return [result] + + on_error = mock.Mock() + with SearchIndexingBufferedSender( + "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error + ) as client: + client._index_documents_actions = mock_fail_index_documents + client._index_key = "id" + client.upload_documents({"id": 0}) + client.flush() + assert on_error.called + + def test_callback_error_on_timeout(self): + def mock_fail_index_documents(actions, timeout=86400): + import time + + if len(actions) > 0: + result = IndexingResult() + result.key = actions[0].additional_properties.get("id") + result.status_code = 400 + result.succeeded = False + self.uploaded = self.uploaded + len(actions) - 1 + time.sleep(1) + return [result] + + on_error = mock.Mock() + with SearchIndexingBufferedSender( + "endpoint", "index name", CREDENTIAL, auto_flush=False, on_error=on_error + ) as client: + client._index_documents_actions = mock_fail_index_documents + client._index_key = "id" + client.upload_documents([{"id": 0}, {"id": 1}]) + with pytest.raises(ServiceResponseTimeoutError): + client.flush(timeout=-1) + assert on_error.call_count == 2 + + def test_callback_progress(self): + def mock_successful_index_documents(actions, timeout=86400): + if len(actions) > 0: + result = IndexingResult() + result.key = actions[0].additional_properties.get("id") + result.status_code = 200 + result.succeeded = True + return [result] + + on_progress = mock.Mock() + on_remove = mock.Mock() + with SearchIndexingBufferedSender( + "endpoint", + "index name", + CREDENTIAL, + auto_flush=False, + on_progress=on_progress, + on_remove=on_remove, + ) as client: + client._index_documents_actions = mock_successful_index_documents + client._index_key = "id" + client.upload_documents({"id": 0}) + client.flush() + assert on_progress.called + assert on_remove.called diff --git a/sdk/search/azure-search-documents/tests/test_index_documents_batch.py b/sdk/search/azure-search-documents/tests/test_index_documents_batch.py new file mode 100644 index 000000000000..c9d8c488d1ce --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_index_documents_batch.py @@ -0,0 +1,69 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import pytest + +from azure.search.documents.models import IndexAction + +from azure.search.documents import IndexDocumentsBatch + +METHOD_NAMES = [ + "add_upload_actions", + "add_delete_actions", + "add_merge_actions", + "add_merge_or_upload_actions", +] + +METHOD_MAP = dict(zip(METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"])) + + +class TestIndexDocumentsBatch: + def test_init(self): + batch = IndexDocumentsBatch() + assert batch.actions == [] + + def test_repr(self): + batch = IndexDocumentsBatch() + assert repr(batch) == "" + + batch._actions = [1, 2, 3] + assert repr(batch) == "" + + # a strict length test here would require constructing an actions list + # with a length of ~10**24, so settle for this simple sanity check on + # an extreme case. + batch_actions = list(range(2000)) + assert len(repr(batch)) <= 1024 + + def test_actions_returns_list_copy(self): + batch = IndexDocumentsBatch() + batch.actions.extend([1, 2, 3]) + assert type(batch.actions) is list + assert batch.actions == [] + assert batch.actions is not batch._actions + + @pytest.mark.parametrize("method_name", METHOD_NAMES) + def test_add_method(self, method_name): + batch = IndexDocumentsBatch() + + method = getattr(batch, method_name) + + method("doc1") + assert len(batch.actions) == 1 + + method("doc2", "doc3") + assert len(batch.actions) == 3 + + method(["doc4", "doc5"]) + assert len(batch.actions) == 5 + + method(("doc6", "doc7")) + assert len(batch.actions) == 7 + + assert all(action.action_type == METHOD_MAP[method_name] for action in batch.actions) + assert all(type(action) == IndexAction for action in batch.actions) + + expected = ["doc{}".format(i) for i in range(1, 8)] + assert [action.additional_properties for action in batch.actions] == expected diff --git a/sdk/search/azure-search-documents/tests/test_index_field_helpers.py b/sdk/search/azure-search-documents/tests/test_index_field_helpers.py new file mode 100644 index 000000000000..8e33f161af67 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_index_field_helpers.py @@ -0,0 +1,90 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from azure.search.documents.indexes.models import ( + ComplexField, + SearchableField, + SimpleField, + SearchFieldDataType, +) + + +def test_edm_contents(): + assert SearchFieldDataType.String == "Edm.String" + assert SearchFieldDataType.Int32 == "Edm.Int32" + assert SearchFieldDataType.Int64 == "Edm.Int64" + assert SearchFieldDataType.Double == "Edm.Double" + assert SearchFieldDataType.Boolean == "Edm.Boolean" + assert SearchFieldDataType.DateTimeOffset == "Edm.DateTimeOffset" + assert SearchFieldDataType.GeographyPoint == "Edm.GeographyPoint" + assert SearchFieldDataType.ComplexType == "Edm.ComplexType" + assert SearchFieldDataType.Collection("foo") == "Collection(foo)" + + +class TestComplexField: + def test_single(self): + fld = ComplexField(name="foo", fields=[]) + assert fld.name == "foo" + assert fld.type == SearchFieldDataType.ComplexType + + assert fld.sortable is None + assert fld.facetable is None + assert fld.searchable is None + assert fld.filterable is None + assert fld.analyzer_name is None + assert fld.search_analyzer_name is None + assert fld.index_analyzer_name is None + assert fld.synonym_map_names is None + + generated_field = fld._to_generated() + assert generated_field.retrievable is None + + def test_collection(self): + fld = ComplexField(name="foo", fields=[], collection=True) + assert fld.name == "foo" + assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.ComplexType) + + assert fld.sortable is None + assert fld.facetable is None + assert fld.searchable is None + assert fld.filterable is None + assert fld.analyzer_name is None + assert fld.search_analyzer_name is None + assert fld.index_analyzer_name is None + assert fld.synonym_map_names is None + + +class TestSimplexField: + def test_defaults(self): + fld = SimpleField(name="foo", type=SearchFieldDataType.Double) + assert fld.name == "foo" + assert fld.type == SearchFieldDataType.Double + assert fld.hidden == False + assert fld.sortable == False + assert fld.facetable == False + assert fld.searchable == False + assert fld.filterable == False + + assert fld.analyzer_name is None + assert fld.search_analyzer_name is None + assert fld.index_analyzer_name is None + assert fld.synonym_map_names is None + + +class TestSearchableField: + def test_defaults(self): + fld = SearchableField(name="foo", collection=True) + assert fld.name == "foo" + assert fld.type == SearchFieldDataType.Collection(SearchFieldDataType.String) + assert fld.hidden == False + assert fld.sortable == False + assert fld.facetable == False + assert fld.searchable == True + assert fld.filterable == False + + assert fld.analyzer_name is None + assert fld.search_analyzer_name is None + assert fld.index_analyzer_name is None + assert fld.synonym_map_names is None diff --git a/sdk/search/azure-search-documents/tests/test_models.py b/sdk/search/azure-search-documents/tests/test_models.py new file mode 100644 index 000000000000..299ee69091a6 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_models.py @@ -0,0 +1,45 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from azure.search.documents.indexes.models import ( + SearchIndexerDataContainer, + SearchIndexerDataSourceConnection, + SearchResourceEncryptionKey, + SearchIndexerSkillset, + ShaperSkill, + SearchIndexer, +) + + +def test_encryption_key_serialization(): + from azure.search.documents.indexes._generated.models import ( + SearchResourceEncryptionKey as SearchResourceEncryptionKeyGen, + ) + + container = SearchIndexerDataContainer(name="container_name") + encryption_key = SearchResourceEncryptionKey( + key_name="key", + key_version="key_version", + vault_uri="vault_uri", + application_id="application_id", + ) + data_source_connection = SearchIndexerDataSourceConnection( + name="datasource-name", + type="azureblob", + connection_string="connection_string", + container=container, + encryption_key=encryption_key, + ) + packed_data_source = data_source_connection._to_generated() + assert isinstance(packed_data_source.encryption_key, SearchResourceEncryptionKeyGen) + + search_indexer = SearchIndexer( + name="indexer-name", + data_source_name="datasource-name", + target_index_name="target-index-name", + encryption_key=encryption_key, + ) + packed_search_indexer = search_indexer._to_generated() + assert isinstance(packed_search_indexer.encryption_key, SearchResourceEncryptionKeyGen) diff --git a/sdk/search/azure-search-documents/tests/test_queries.py b/sdk/search/azure-search-documents/tests/test_queries.py new file mode 100644 index 000000000000..dacac2c74ad1 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_queries.py @@ -0,0 +1,165 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import pytest +from unittest import mock + +from azure.search.documents._generated.models import ( + AutocompleteRequest, + SearchRequest, + SuggestRequest, +) + +from azure.search.documents._queries import AutocompleteQuery, SuggestQuery, SearchQuery + + +class TestAutocompleteQuery: + def test_init(self): + query = AutocompleteQuery(search_text="text", suggester_name="sg") + assert type(query.request) is AutocompleteRequest + assert query.request.filter is None + + @mock.patch("azure.search.documents._queries.AutocompleteQuery._request_type") + def test_kwargs_forwarded(self, mock_request): + mock_request.return_value = None + AutocompleteQuery(foo=10, bar=20) + assert mock_request.called + assert mock_request.call_args[0] == () + assert mock_request.call_args[1] == {"foo": 10, "bar": 20} + + def test_repr(self): + query = AutocompleteQuery(search_text="foo bar", suggester_name="sg") + assert repr(query) == "" + + query = AutocompleteQuery(search_text="aaaaabbbbb" * 200, suggester_name="sg") + assert len(repr(query)) == 1024 + + def test_filter(self): + query = AutocompleteQuery(search_text="text", suggester_name="sg") + assert query.request.filter is None + query.filter("expr0") + assert query.request.filter == "expr0" + + query = AutocompleteQuery(search_text="text", suggester_name="sg", filter="expr1") + assert query.request.filter == "expr1" + query.filter("expr2") + assert query.request.filter == "expr2" + + +class TestSearchQuery: + def test_init(self): + query = SearchQuery() + assert type(query.request) is SearchRequest + assert query.request.filter is None + assert query.request.order_by is None + assert query.request.select is None + + @mock.patch("azure.search.documents._queries.SearchQuery._request_type") + def test_kwargs_forwarded(self, mock_request): + mock_request.return_value = None + SearchQuery(foo=10, bar=20) + assert mock_request.called + assert mock_request.call_args[0] == () + assert mock_request.call_args[1] == {"foo": 10, "bar": 20} + + def test_repr(self): + query = SearchQuery() + assert repr(query) == "" + + query = SearchQuery(search_text="foo bar", suggester_name="sg") + assert repr(query) == "" + + query = SearchQuery(search_text="aaaaabbbbb" * 200) + assert len(repr(query)) == 1024 + + def test_filter(self): + query = SearchQuery() + assert query.request.filter is None + query.filter("expr0") + assert query.request.filter == "expr0" + + query = SearchQuery(filter="expr0") + assert query.request.filter == "expr0" + query.filter("expr1") + assert query.request.filter == "expr1" + + def test_order_by(self): + query = SearchQuery() + assert query.request.order_by is None + query.order_by("f0") + assert query.request.order_by == "f0" + query.order_by("f1,f2") + assert query.request.order_by == "f1,f2" + query.order_by("f3", "f4") + assert query.request.order_by == "f3,f4" + + query = SearchQuery(order_by="f0") + assert query.request.order_by == "f0" + query.order_by("f1,f2") + assert query.request.order_by == "f1,f2" + query.order_by("f3", "f4") + assert query.request.order_by == "f3,f4" + + with pytest.raises(ValueError) as e: + query.order_by() + assert str(e) == "At least one field must be provided" + + def test_select(self): + query = SearchQuery() + assert query.request.select is None + query.select("f0") + assert query.request.select == "f0" + query.select("f1,f2") + assert query.request.select == "f1,f2" + query.select("f3", "f4") + assert query.request.select == "f3,f4" + + query = SearchQuery(select="f0") + assert query.request.select == "f0" + query.select("f1,f2") + assert query.request.select == "f1,f2" + query.select("f3", "f4") + assert query.request.select == "f3,f4" + + str = ["f1", "f2"] + query.select(str) + assert query.request.select == "f1,f2" + + with pytest.raises(ValueError) as e: + query.select() + assert str(e) == "At least one field must be provided" + + +class TestSuggestQuery: + def test_init(self): + query = SuggestQuery(search_text="text", suggester_name="sg") + assert type(query.request) is SuggestRequest + assert query.request.filter is None + + @mock.patch("azure.search.documents._queries.SuggestQuery._request_type") + def test_kwargs_forwarded(self, mock_request): + mock_request.return_value = None + SuggestQuery(foo=10, bar=20) + assert mock_request.called + assert mock_request.call_args[0] == () + assert mock_request.call_args[1] == {"foo": 10, "bar": 20} + + def test_repr(self): + query = SuggestQuery(search_text="foo bar", suggester_name="sg") + assert repr(query) == "" + + query = SuggestQuery(search_text="aaaaabbbbb" * 200, suggester_name="sg") + assert len(repr(query)) == 1024 + + def test_filter(self): + query = SuggestQuery(search_text="text", suggester_name="sg") + assert query.request.filter is None + query.filter("expr0") + assert query.request.filter == "expr0" + + query = SuggestQuery(search_text="text", suggester_name="sg", filter="expr1") + assert query.request.filter == "expr1" + query.filter("expr2") + assert query.request.filter == "expr2" diff --git a/sdk/search/azure-search-documents/tests/test_regex_flags.py b/sdk/search/azure-search-documents/tests/test_regex_flags.py new file mode 100644 index 000000000000..cee471b5d1df --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_regex_flags.py @@ -0,0 +1,102 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from azure.search.documents.indexes.models import ( + SearchIndex, + RegexFlags, + PatternAnalyzer, + PatternTokenizer, +) +from azure.search.documents.indexes._generated.models import ( + PatternAnalyzer as _PatternAnalyzer, + PatternTokenizer as _PatternTokenizer, +) + + +def test_unpack_search_index(): + pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags="CANON_EQ") + analyzers = [] + analyzers.append(pattern_analyzer) + pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags="CANON_EQ") + tokenizers = [] + tokenizers.append(pattern_tokenizer) + index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) + result = SearchIndex._from_generated(index) + assert isinstance(result.analyzers[0], PatternAnalyzer) + assert isinstance(result.analyzers[0].flags, list) + assert result.analyzers[0].flags[0] == "CANON_EQ" + assert isinstance(result.tokenizers[0], PatternTokenizer) + assert isinstance(result.tokenizers[0].flags, list) + assert result.tokenizers[0].flags[0] == "CANON_EQ" + + +def test_multi_unpack_search_index(): + pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags="CANON_EQ|MULTILINE") + analyzers = [] + analyzers.append(pattern_analyzer) + pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags="CANON_EQ|MULTILINE") + tokenizers = [] + tokenizers.append(pattern_tokenizer) + index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) + result = SearchIndex._from_generated(index) + assert isinstance(result.analyzers[0], PatternAnalyzer) + assert isinstance(result.analyzers[0].flags, list) + assert result.analyzers[0].flags[0] == "CANON_EQ" + assert result.analyzers[0].flags[1] == "MULTILINE" + assert isinstance(result.tokenizers[0], PatternTokenizer) + assert isinstance(result.tokenizers[0].flags, list) + assert result.tokenizers[0].flags[0] == "CANON_EQ" + assert result.tokenizers[0].flags[1] == "MULTILINE" + + +def test_unpack_search_index_enum(): + pattern_analyzer = _PatternAnalyzer(name="test_analyzer", flags=RegexFlags.canon_eq) + analyzers = [] + analyzers.append(pattern_analyzer) + pattern_tokenizer = _PatternTokenizer(name="test_tokenizer", flags=RegexFlags.canon_eq) + tokenizers = [] + tokenizers.append(pattern_tokenizer) + index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) + result = SearchIndex._from_generated(index) + assert isinstance(result.analyzers[0], PatternAnalyzer) + assert isinstance(result.analyzers[0].flags, list) + assert result.analyzers[0].flags[0] == "CANON_EQ" + assert isinstance(result.tokenizers[0], PatternTokenizer) + assert isinstance(result.tokenizers[0].flags, list) + assert result.tokenizers[0].flags[0] == "CANON_EQ" + + +def test_pack_search_index(): + pattern_analyzer = PatternAnalyzer(name="test_analyzer", flags=["CANON_EQ"]) + analyzers = [] + analyzers.append(pattern_analyzer) + pattern_tokenizer = PatternTokenizer(name="test_tokenizer", flags=["CANON_EQ"]) + tokenizers = [] + tokenizers.append(pattern_tokenizer) + index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) + result = index._to_generated() + assert isinstance(result.analyzers[0], _PatternAnalyzer) + assert isinstance(result.analyzers[0].flags, str) + assert result.analyzers[0].flags == "CANON_EQ" + assert isinstance(result.tokenizers[0], _PatternTokenizer) + assert isinstance(result.tokenizers[0].flags, str) + assert result.tokenizers[0].flags == "CANON_EQ" + + +def test_multi_pack_search_index(): + pattern_analyzer = PatternAnalyzer(name="test_analyzer", flags=["CANON_EQ", "MULTILINE"]) + analyzers = [] + analyzers.append(pattern_analyzer) + pattern_tokenizer = PatternTokenizer(name="test_analyzer", flags=["CANON_EQ", "MULTILINE"]) + tokenizers = [] + tokenizers.append(pattern_tokenizer) + index = SearchIndex(name="test", fields=None, analyzers=analyzers, tokenizers=tokenizers) + result = index._to_generated() + assert isinstance(result.analyzers[0], _PatternAnalyzer) + assert isinstance(result.analyzers[0].flags, str) + assert result.analyzers[0].flags == "CANON_EQ|MULTILINE" + assert isinstance(result.tokenizers[0], _PatternTokenizer) + assert isinstance(result.tokenizers[0].flags, str) + assert result.tokenizers[0].flags == "CANON_EQ|MULTILINE" diff --git a/sdk/search/azure-search-documents/tests/test_search_client.py b/sdk/search/azure-search-documents/tests/test_search_client.py new file mode 100644 index 000000000000..f8833f55fdec --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_client.py @@ -0,0 +1,323 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import pytest +from unittest import mock +from azure.core.paging import ItemPaged +from azure.core.credentials import AzureKeyCredential + +from azure.search.documents._generated.models import ( + SearchDocumentsResult, + SearchResult, +) +from azure.search.documents._search_client import SearchPageIterator + +from azure.search.documents import ( + IndexDocumentsBatch, + SearchClient, + RequestEntityTooLargeError, + ApiVersion, +) +from azure.search.documents._utils import odata, get_answer_query + +CREDENTIAL = AzureKeyCredential(key="test_api_key") + +CRUD_METHOD_NAMES = [ + "upload_documents", + "delete_documents", + "merge_documents", + "merge_or_upload_documents", +] + +CRUD_METHOD_MAP = dict(zip(CRUD_METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"])) + + +class Test_odata: + def test_const(self): + assert odata("no escapes") == "no escapes" + + def test_numbers(self): + assert odata("foo eq {foo}", foo=10) == "foo eq 10" + + def test_string(self): + assert odata("foo eq {foo}", foo="a string") == "foo eq 'a string'" + + def test_mixed(self): + expected = "foo eq 'a string' and bar le 10" + out = odata("foo eq {foo} and bar le {bar}", foo="a string", bar=10) + assert out == expected + + def test_escape_single_quote(self): + assert odata("foo eq {foo}", foo="a '' str'ing") == "foo eq 'a '''' str''ing'" + + def test_prevent_double_quoting(self): + assert odata("foo eq '{foo}'", foo="a string") == "foo eq 'a string'" + + +class TestAnswerQuery: + def test_no_args(self): + assert get_answer_query() is None + + def test_query_answer(self): + assert get_answer_query("query") == "query" + + def test_query_answer_count(self): + assert get_answer_query("query", 5) == "query|count-5" + + def test_query_answer_threshold(self): + assert get_answer_query("query", query_answer_threshold=0.5) == "query|threshold-0.5" + + def test_query_answer_count_threshold(self): + assert get_answer_query("query", 5, 0.5) == "query|count-5,threshold-0.5" + + +class TestSearchClient: + def test_init(self): + client = SearchClient("endpoint", "index name", CREDENTIAL) + assert client._headers == { + "api-key": "test_api_key", + "Accept": "application/json;odata.metadata=none", + } + + def test_credential_roll(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchClient("endpoint", "index name", credential) + assert client._headers == { + "api-key": "old_api_key", + "Accept": "application/json;odata.metadata=none", + } + credential.update("new_api_key") + assert client._headers == { + "api-key": "new_api_key", + "Accept": "application/json;odata.metadata=none", + } + + def test_headers_merge(self): + credential = AzureKeyCredential(key="test_api_key") + client = SearchClient("endpoint", "index name", credential) + orig = {"foo": "bar"} + result = client._merge_client_headers(orig) + assert result is not orig + assert result == { + "api-key": "test_api_key", + "Accept": "application/json;odata.metadata=none", + "foo": "bar", + } + + def test_repr(self): + client = SearchClient("endpoint", "index name", CREDENTIAL) + assert repr(client) == "".format(repr("endpoint"), repr("index name")) + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.count") + def test_get_document_count(self, mock_count): + client = SearchClient("endpoint", "index name", CREDENTIAL) + client.get_document_count() + assert mock_count.called + assert mock_count.call_args[0] == () + assert len(mock_count.call_args[1]) == 1 + assert mock_count.call_args[1]["headers"] == client._headers + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.get") + def test_get_document(self, mock_get): + client = SearchClient("endpoint", "index name", CREDENTIAL) + client.get_document("some_key") + assert mock_get.called + assert mock_get.call_args[0] == () + assert len(mock_get.call_args[1]) == 3 + assert mock_get.call_args[1]["headers"] == client._headers + assert mock_get.call_args[1]["key"] == "some_key" + assert mock_get.call_args[1]["selected_fields"] == None + + mock_get.reset() + + client.get_document("some_key", selected_fields="foo") + assert mock_get.called + assert mock_get.call_args[0] == () + assert len(mock_get.call_args[1]) == 3 + assert mock_get.call_args[1]["headers"] == client._headers + assert mock_get.call_args[1]["key"] == "some_key" + assert mock_get.call_args[1]["selected_fields"] == "foo" + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post") + def test_search_query_argument(self, mock_search_post): + client = SearchClient("endpoint", "index name", CREDENTIAL) + result = client.search(search_text="search text") + assert isinstance(result, ItemPaged) + assert result._page_iterator_class is SearchPageIterator + search_result = SearchDocumentsResult() + search_result.results = [SearchResult(additional_properties={"key": "val"})] + mock_search_post.return_value = search_result + assert not mock_search_post.called + next(result) + assert mock_search_post.called + assert mock_search_post.call_args[0] == () + assert mock_search_post.call_args[1]["search_request"].search_text == "search text" + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.suggest_post") + def test_suggest_query_argument(self, mock_suggest_post): + client = SearchClient("endpoint", "index name", CREDENTIAL) + result = client.suggest(search_text="search text", suggester_name="sg") + assert mock_suggest_post.called + assert mock_suggest_post.call_args[0] == () + assert mock_suggest_post.call_args[1]["headers"] == client._headers + assert mock_suggest_post.call_args[1]["suggest_request"].search_text == "search text" + + def test_suggest_bad_argument(self): + client = SearchClient("endpoint", "index name", CREDENTIAL) + with pytest.raises(TypeError) as e: + client.suggest("bad_query") + assert str(e) == "Expected a SuggestQuery for 'query', but got {}".format(repr("bad_query")) + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post") + def test_get_count_reset_continuation_token(self, mock_search_post): + client = SearchClient("endpoint", "index name", CREDENTIAL) + result = client.search(search_text="search text") + assert isinstance(result, ItemPaged) + assert result._page_iterator_class is SearchPageIterator + search_result = SearchDocumentsResult() + search_result.results = [SearchResult(additional_properties={"key": "val"})] + mock_search_post.return_value = search_result + result.__next__() + result._first_page_iterator_instance.continuation_token = "fake token" + result.get_count() + assert not result._first_page_iterator_instance.continuation_token + + @mock.patch( + "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.autocomplete_post" + ) + def test_autocomplete_query_argument(self, mock_autocomplete_post): + client = SearchClient("endpoint", "index name", CREDENTIAL) + result = client.autocomplete(search_text="search text", suggester_name="sg") + assert mock_autocomplete_post.called + assert mock_autocomplete_post.call_args[0] == () + assert mock_autocomplete_post.call_args[1]["headers"] == client._headers + assert mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text == "search text" + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.count") + def test_get_document_count_v2020_06_30(self, mock_count): + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) + client.get_document_count() + assert mock_count.called + assert mock_count.call_args[0] == () + assert len(mock_count.call_args[1]) == 1 + assert mock_count.call_args[1]["headers"] == client._headers + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.get") + def test_get_document_v2020_06_30(self, mock_get): + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) + client.get_document("some_key") + assert mock_get.called + assert mock_get.call_args[0] == () + assert len(mock_get.call_args[1]) == 3 + assert mock_get.call_args[1]["headers"] == client._headers + assert mock_get.call_args[1]["key"] == "some_key" + assert mock_get.call_args[1]["selected_fields"] == None + + mock_get.reset() + + client.get_document("some_key", selected_fields="foo") + assert mock_get.called + assert mock_get.call_args[0] == () + assert len(mock_get.call_args[1]) == 3 + assert mock_get.call_args[1]["headers"] == client._headers + assert mock_get.call_args[1]["key"] == "some_key" + assert mock_get.call_args[1]["selected_fields"] == "foo" + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.search_post") + def test_search_query_argument_v2020_06_30(self, mock_search_post): + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) + result = client.search(search_text="search text") + assert isinstance(result, ItemPaged) + assert result._page_iterator_class is SearchPageIterator + search_result = SearchDocumentsResult() + search_result.results = [SearchResult(additional_properties={"key": "val"})] + mock_search_post.return_value = search_result + assert not mock_search_post.called + next(result) + assert mock_search_post.called + assert mock_search_post.call_args[0] == () + assert mock_search_post.call_args[1]["search_request"].search_text == "search text" + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.suggest_post") + def test_suggest_query_argument_v2020_06_30(self, mock_suggest_post): + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) + result = client.suggest(search_text="search text", suggester_name="sg") + assert mock_suggest_post.called + assert mock_suggest_post.call_args[0] == () + assert mock_suggest_post.call_args[1]["headers"] == client._headers + assert mock_suggest_post.call_args[1]["suggest_request"].search_text == "search text" + + @mock.patch( + "azure.search.documents._generated.operations._documents_operations.DocumentsOperations.autocomplete_post" + ) + def test_autocomplete_query_argument_v2020_06_30(self, mock_autocomplete_post): + client = SearchClient("endpoint", "index name", CREDENTIAL, api_version=ApiVersion.V2020_06_30) + result = client.autocomplete(search_text="search text", suggester_name="sg") + assert mock_autocomplete_post.called + assert mock_autocomplete_post.call_args[0] == () + assert mock_autocomplete_post.call_args[1]["headers"] == client._headers + assert mock_autocomplete_post.call_args[1]["autocomplete_request"].search_text == "search text" + + def test_autocomplete_bad_argument(self): + client = SearchClient("endpoint", "index name", CREDENTIAL) + with pytest.raises(TypeError) as e: + client.autocomplete("bad_query") + assert str(e) == "Expected a AutocompleteQuery for 'query', but got {}".format(repr("bad_query")) + + @pytest.mark.parametrize("arg", [[], ["doc1"], ["doc1", "doc2"]], ids=lambda x: str(len(x)) + " docs") + @pytest.mark.parametrize("method_name", CRUD_METHOD_NAMES) + def test_add_method(self, arg, method_name): + with mock.patch.object(SearchClient, "index_documents", return_value=None) as mock_index_documents: + client = SearchClient("endpoint", "index name", CREDENTIAL) + + method = getattr(client, method_name) + method(arg, extra="foo") + + assert mock_index_documents.called + assert len(mock_index_documents.call_args[0]) == 1 + batch = mock_index_documents.call_args[0][0] + assert isinstance(batch, IndexDocumentsBatch) + assert all(action.action_type == CRUD_METHOD_MAP[method_name] for action in batch.actions) + assert [action.additional_properties for action in batch.actions] == arg + assert mock_index_documents.call_args[1]["headers"] == client._headers + assert mock_index_documents.call_args[1]["extra"] == "foo" + + @mock.patch("azure.search.documents._generated.operations._documents_operations.DocumentsOperations.index") + def test_index_documents(self, mock_index): + client = SearchClient("endpoint", "index name", CREDENTIAL) + + batch = IndexDocumentsBatch() + actions = batch.add_upload_actions("upload1") + assert len(actions) == 1 + for x in actions: + assert x.action_type == "upload" + actions = batch.add_delete_actions("delete1", "delete2") + assert len(actions) == 2 + for x in actions: + assert x.action_type == "delete" + actions = batch.add_merge_actions(["merge1", "merge2", "merge3"]) + for x in actions: + assert x.action_type == "merge" + actions = batch.add_merge_or_upload_actions("merge_or_upload1") + for x in actions: + assert x.action_type == "mergeOrUpload" + + client.index_documents(batch, extra="foo") + assert mock_index.called + assert mock_index.call_args[0] == () + assert mock_index.call_args[1]["headers"] == client._headers + assert mock_index.call_args[1]["extra"] == "foo" + + def test_request_too_large_error(self): + with mock.patch.object( + SearchClient, + "_index_documents_actions", + side_effect=RequestEntityTooLargeError("Error"), + ): + client = SearchClient("endpoint", "index name", CREDENTIAL) + batch = IndexDocumentsBatch() + batch.add_upload_actions("upload1") + with pytest.raises(RequestEntityTooLargeError): + client.index_documents(batch, extra="foo") diff --git a/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py b/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py new file mode 100644 index 000000000000..5c1500615dee --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_client_basic_live.py @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core.exceptions import HttpResponseError +from azure.search.documents import SearchClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClient(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_get_document_count(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + assert client.get_document_count() == 10 + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_get_document(self, endpoint, index_name, index_batch): + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + for hotel_id in range(1, 11): + result = client.get_document(key=str(hotel_id)) + expected = index_batch["value"][hotel_id - 1] + assert result.get("hotelId") == expected.get("hotelId") + assert result.get("hotelName") == expected.get("hotelName") + assert result.get("description") == expected.get("description") + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_get_document_missing(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + with pytest.raises(HttpResponseError): + client.get_document(key="1000") diff --git a/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py b/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py new file mode 100644 index 000000000000..30d6f221bfd1 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_client_buffered_sender_live.py @@ -0,0 +1,168 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +import time +from azure.core.exceptions import HttpResponseError +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchIndexingBufferedSender, SearchClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential +from search_service_preparer import SearchEnvVarPreparer, search_decorator + +TIME_TO_SLEEP = 3 + + +class TestSearchIndexingBufferedSender(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_search_client_index_buffered_sender(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + batch_client = SearchIndexingBufferedSender(endpoint, index_name, get_credential(), retry_backoff_factor=60) + try: + doc_count = 10 + doc_count = self._test_upload_documents_new(client, batch_client, doc_count) + doc_count = self._test_upload_documents_existing(client, batch_client, doc_count) + doc_count = self._test_delete_documents_existing(client, batch_client, doc_count) + doc_count = self._test_delete_documents_missing(client, batch_client, doc_count) + doc_count = self._test_merge_documents_existing(client, batch_client, doc_count) + doc_count = self._test_merge_documents_missing(client, batch_client, doc_count) + doc_count = self._test_merge_or_upload_documents(client, batch_client, doc_count) + finally: + batch_client.close() + + def _test_upload_documents_new(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + docs = [ + {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + batch_client.upload_documents(docs) + doc_count += 2 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + for doc in docs: + result = client.get_document(key=doc["hotelId"]) + assert result["hotelId"] == doc["hotelId"] + assert result["hotelName"] == doc["hotelName"] + assert result["rating"] == doc["rating"] + assert result["rooms"] == doc["rooms"] + return doc_count + + def _test_upload_documents_existing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # add one new and one existing + docs = [ + {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + batch_client.upload_documents(docs) + doc_count += 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + return doc_count + + def _test_delete_documents_existing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + docs = [{"hotelId": "3"}, {"hotelId": "4"}] + batch_client.delete_documents(docs) + doc_count -= 2 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + client.get_document(key="3") + + with pytest.raises(HttpResponseError): + client.get_document(key="4") + return doc_count + + def _test_delete_documents_missing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # delete one existing and one missing + docs = [{"hotelId": "1003"}, {"hotelId": "2"}] + batch_client.delete_documents(docs) + doc_count -= 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + with pytest.raises(HttpResponseError): + client.get_document(key="1003") + with pytest.raises(HttpResponseError): + client.get_document(key="2") + return doc_count + + def _test_merge_documents_existing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] + batch_client.merge_documents(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + result = client.get_document(key="5") + assert result["rating"] == 1 + + result = client.get_document(key="6") + assert result["rating"] == 2 + return doc_count + + def _test_merge_documents_missing(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # merge to one existing and one missing document + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + batch_client.merge_documents(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + client.get_document(key="1003") + + result = client.get_document(key="1") + assert result["rating"] == 2 + return doc_count + + def _test_merge_or_upload_documents(self, client, batch_client, doc_count): + batch_client._batch_action_count = 2 + # merge to one existing and one missing + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + batch_client.merge_or_upload_documents(docs) + doc_count += 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + result = client.get_document(key="1003") + assert result["rating"] == 1 + + result = client.get_document(key="1") + assert result["rating"] == 2 + return doc_count diff --git a/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py b/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py new file mode 100644 index 000000000000..52219a0819a0 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_client_index_document_live.py @@ -0,0 +1,167 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +import time +from azure.core.exceptions import HttpResponseError +from azure.search.documents import SearchClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential +from search_service_preparer import SearchEnvVarPreparer, search_decorator + +TIME_TO_SLEEP = 3 + + +class TestSearchClientIndexDocument(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_search_client_index_document(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + doc_count = 10 + doc_count = self._test_upload_documents_new(client, doc_count) + doc_count = self._test_upload_documents_existing(client, doc_count) + doc_count = self._test_delete_documents_existing(client, doc_count) + doc_count = self._test_delete_documents_missing(client, doc_count) + doc_count = self._test_merge_documents_existing(client, doc_count) + doc_count = self._test_merge_documents_missing(client, doc_count) + doc_count = self._test_merge_or_upload_documents(client, doc_count) + + def _test_upload_documents_new(self, client, doc_count): + docs = [ + {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + results = client.upload_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {201} + doc_count += len(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + for doc in docs: + result = client.get_document(key=doc["hotelId"]) + assert result["hotelId"] == doc["hotelId"] + assert result["hotelName"] == doc["hotelName"] + assert result["rating"] == doc["rating"] + assert result["rooms"] == doc["rooms"] + return doc_count + + def _test_upload_documents_existing(self, client, doc_count): + # add one new and one existing + docs = [ + {"hotelId": "1002", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, + {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, + ] + results = client.upload_documents(docs) + assert len(results) == len(docs) + doc_count += 1 + assert set(x.status_code for x in results) == {200, 201} + return doc_count + + def _test_delete_documents_existing(self, client, doc_count): + docs = [{"hotelId": "3"}, {"hotelId": "4"}] + results = client.delete_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200} + doc_count -= len(docs) + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + client.get_document(key="3") + + with pytest.raises(HttpResponseError): + client.get_document(key="4") + return doc_count + + def _test_delete_documents_missing(self, client, doc_count): + # delete one existing and one missing + docs = [{"hotelId": "1003"}, {"hotelId": "2"}] + results = client.delete_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200} + doc_count -= 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + client.get_document(key="1003") + + with pytest.raises(HttpResponseError): + client.get_document(key="2") + return doc_count + + def _test_merge_documents_existing(self, client, doc_count): + docs = [{"hotelId": "5", "rating": 1}, {"hotelId": "6", "rating": 2}] + results = client.merge_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200} + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + test = client.get_document_count() + assert client.get_document_count() == doc_count + + result = client.get_document(key="5") + assert result["rating"] == 1 + + result = client.get_document(key="6") + assert result["rating"] == 2 + return doc_count + + def _test_merge_documents_missing(self, client, doc_count): + # merge to one existing and one missing document + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + results = client.merge_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200, 404} + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + with pytest.raises(HttpResponseError): + client.get_document(key="1003") + + result = client.get_document(key="1") + assert result["rating"] == 2 + return doc_count + + def _test_merge_or_upload_documents(self, client, doc_count): + # merge to one existing and one missing + docs = [{"hotelId": "1003", "rating": 1}, {"hotelId": "1", "rating": 2}] + results = client.merge_or_upload_documents(docs) + assert len(results) == len(docs) + assert set(x.status_code for x in results) == {200, 201} + doc_count += 1 + + # There can be some lag before a document is searchable + if self.is_live: + time.sleep(TIME_TO_SLEEP) + + assert client.get_document_count() == doc_count + + result = client.get_document(key="1003") + assert result["rating"] == 1 + + result = client.get_document(key="1") + assert result["rating"] == 2 + return doc_count diff --git a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py new file mode 100644 index 000000000000..af86da2542c6 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py @@ -0,0 +1,134 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.search.documents import SearchClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClient(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_search_client(self, endpoint, index_name): + client = SearchClient(endpoint, index_name, get_credential(), retry_backoff_factor=60) + self._test_get_search_simple(client) + self._test_get_search_simple_with_top(client) + self._test_get_search_filter(client) + self._test_get_search_filter_array(client) + self._test_get_search_counts(client) + self._test_get_search_coverage(client) + self._test_get_search_facets_none(client) + self._test_get_search_facets_result(client) + self._test_autocomplete(client) + self._test_suggest(client) + + def _test_get_search_simple(self, client): + results = list(client.search(search_text="hotel")) + assert len(results) == 7 + + results = list(client.search(search_text="motel")) + assert len(results) == 2 + + def _test_get_search_simple_with_top(self, client): + results = list(client.search(search_text="hotel", top=3)) + assert len(results) == 3 + + results = list(client.search(search_text="motel", top=3)) + assert len(results) == 2 + + def _test_get_search_filter(self, client): + select = ["hotelName", "category", "description"] + results = list( + client.search( + search_text="WiFi", + filter="category eq 'Budget'", + select=",".join(select), + order_by="hotelName desc", + ) + ) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) + expected = { + "category", + "hotelName", + "description", + "@search.score", + "@search.reranker_score", + "@search.highlights", + "@search.captions", + "@search.document_debug_info", + "@search.reranker_boosted_score", + } + assert all(set(x) == expected for x in results) + assert all(x["category"] == "Budget" for x in results) + + def _test_get_search_filter_array(self, client): + select = ["hotelName", "category", "description"] + results = list( + client.search( + search_text="WiFi", + filter="category eq 'Budget'", + select=select, + order_by="hotelName desc", + ) + ) + assert [x["hotelName"] for x in results] == sorted([x["hotelName"] for x in results], reverse=True) + expected = { + "category", + "hotelName", + "description", + "@search.score", + "@search.reranker_score", + "@search.highlights", + "@search.captions", + "@search.document_debug_info", + "@search.reranker_boosted_score", + } + assert all(set(x) == expected for x in results) + assert all(x["category"] == "Budget" for x in results) + + def _test_get_search_counts(self, client): + results = client.search(search_text="hotel") + assert results.get_count() is None + + results = client.search(search_text="hotel", include_total_count=True) + assert results.get_count() == 7 + + def _test_get_search_coverage(self, client): + results = client.search(search_text="hotel") + assert results.get_coverage() is None + + results = client.search(search_text="hotel", minimum_coverage=50.0) + cov = results.get_coverage() + assert isinstance(cov, float) + assert cov >= 50.0 + + def _test_get_search_facets_none(self, client): + select = ("hotelName", "category", "description") + results = client.search(search_text="WiFi", select=",".join(select)) + assert results.get_facets() is None + + def _test_get_search_facets_result(self, client): + select = ("hotelName", "category", "description") + results = client.search(search_text="WiFi", facets=["category"], select=",".join(select)) + assert results.get_facets() == { + "category": [ + {"value": "Budget", "count": 4}, + {"value": "Luxury", "count": 1}, + ] + } + + def _test_autocomplete(self, client): + results = client.autocomplete(search_text="mot", suggester_name="sg") + assert results == [{"text": "motel", "query_plus_text": "motel"}] + + def _test_suggest(self, client): + results = client.suggest(search_text="mot", suggester_name="sg") + assert results == [ + {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, + {"hotelId": "9", "text": "Secret Point Motel"}, + ] diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client.py b/sdk/search/azure-search-documents/tests/test_search_index_client.py new file mode 100644 index 000000000000..73973e36d3f1 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_index_client.py @@ -0,0 +1,130 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import pytest +from unittest import mock + +from azure.core.credentials import AzureKeyCredential +from azure.search.documents import SearchClient, ApiVersion +from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient +from azure.search.documents.indexes.models import ( + SearchIndexerDataContainer, + SearchIndexerDataSourceConnection, +) + +CREDENTIAL = AzureKeyCredential(key="test_api_key") + + +class TestSearchIndexClient: + def test_index_init(self): + client = SearchIndexClient("endpoint", CREDENTIAL) + assert client._headers == { + "api-key": "test_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_index_credential_roll(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential, retry_backoff_factor=60) + assert client._headers == { + "api-key": "old_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + credential.update("new_api_key") + assert client._headers == { + "api-key": "new_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_get_search_client(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential) + search_client = client.get_search_client("index") + assert isinstance(search_client, SearchClient) + + def test_get_search_client_inherit_api_version(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential, api_version=ApiVersion.V2020_06_30) + search_client = client.get_search_client("index") + assert isinstance(search_client, SearchClient) + assert search_client._api_version == ApiVersion.V2020_06_30 + + @mock.patch( + "azure.search.documents.indexes._generated.operations._search_service_client_operations._SearchServiceClientOperationsMixin.get_service_statistics" + ) + def test_get_service_statistics(self, mock_get_stats): + client = SearchIndexClient("endpoint", CREDENTIAL) + client.get_service_statistics() + assert mock_get_stats.called + assert mock_get_stats.call_args[0] == () + assert mock_get_stats.call_args[1] == {"headers": client._headers} + + @mock.patch( + "azure.search.documents.indexes._generated.operations._search_service_client_operations._SearchServiceClientOperationsMixin.get_service_statistics" + ) + def test_get_service_statistics_v2020_06_30(self, mock_get_stats): + client = SearchIndexClient("endpoint", CREDENTIAL, api_version=ApiVersion.V2020_06_30) + client.get_service_statistics() + assert mock_get_stats.called + assert mock_get_stats.call_args[0] == () + assert mock_get_stats.call_args[1] == {"headers": client._headers} + + def test_index_endpoint_https(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexClient("endpoint", credential) + assert client._endpoint.startswith("https") + + client = SearchIndexClient("https://endpoint", credential) + assert client._endpoint.startswith("https") + + with pytest.raises(ValueError): + client = SearchIndexClient("http://endpoint", credential) + + with pytest.raises(ValueError): + client = SearchIndexClient(12345, credential) + + +class TestSearchIndexerClient: + def test_indexer_init(self): + client = SearchIndexerClient("endpoint", CREDENTIAL) + assert client._headers == { + "api-key": "test_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_indexer_credential_roll(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexerClient("endpoint", credential) + assert client._headers == { + "api-key": "old_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + credential.update("new_api_key") + assert client._headers == { + "api-key": "new_api_key", + "Accept": "application/json;odata.metadata=minimal", + } + + def test_indexer_endpoint_https(self): + credential = AzureKeyCredential(key="old_api_key") + client = SearchIndexerClient("endpoint", credential) + assert client._endpoint.startswith("https") + + client = SearchIndexerClient("https://endpoint", credential) + assert client._endpoint.startswith("https") + + with pytest.raises(ValueError): + client = SearchIndexerClient("http://endpoint", credential) + + with pytest.raises(ValueError): + client = SearchIndexerClient(12345, credential) + + def test_datasource_with_empty_connection_string(self): + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name="test", type="azureblob", connection_string="", container=container + ) + packed_data_source_connection = data_source_connection._to_generated() + assert packed_data_source_connection.credentials.connection_string == "" diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py new file mode 100644 index 000000000000..0e91ad5774fa --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_alias_live.py @@ -0,0 +1,108 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from unicodedata import name +import pytest + +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes import SearchIndexClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential +from azure.search.documents.indexes.models import ( + AnalyzeTextOptions, + CorsOptions, + SearchIndex, + ScoringProfile, + SimpleField, + SearchFieldDataType, + SearchAlias, +) + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClientAlias(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_alias(self, endpoint): + client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) + aliases = ["resort", "motel"] + index_name = next(client.list_index_names()) + self._test_list_aliases_empty(client) + self._test_create_alias(client, aliases[0], index_name) + + self._test_create_or_update_alias(client, aliases[1], index_name) + + # point an old alias to a new index + new_index_name = "hotel" + self._test_update_alias_to_new_index(client, aliases[1], new_index_name, index_name) + + self._test_get_alias(client, aliases) + + self._test_list_aliases(client, aliases) + self._test_delete_aliases(client) + + def _test_list_aliases_empty(self, client): + result = client.list_aliases() + with pytest.raises(StopIteration): + next(result) + + def _test_create_alias(self, client, alias_name, index_name): + alias = SearchAlias(name=alias_name, indexes=[index_name]) + result = client.create_alias(alias) + assert result.name == alias_name + assert set(result.indexes) == {index_name} + + def _test_create_or_update_alias(self, client, alias_name, index_name): + alias = SearchAlias(name=alias_name, indexes=[index_name]) + result = client.create_or_update_alias(alias) + assert result.name == alias_name + assert set(result.indexes) == {index_name} + + def _test_update_alias_to_new_index(self, client, alias_name, new_index, old_index): + self._create_index(client, new_index) + alias = SearchAlias(name=alias_name, indexes=[new_index]) + result = client.create_or_update_alias(alias) + + assert result.name == alias_name + assert result.indexes[0] != old_index + assert result.indexes[0] == new_index + + def _test_get_alias(self, client, aliases): + for alias in aliases: + result = client.get_alias(alias) + assert result + assert result.name == alias + + def _test_list_aliases(self, client, aliases): + result = {alias for alias in client.list_alias_names()} + assert result == set(aliases) + + def _test_delete_aliases(self, client): + aliases = client.list_aliases() + + for alias in aliases: + client.delete_alias(alias) + with pytest.raises(HttpResponseError): + result = client.get_alias(alias) + + def _create_index(self, client, index_name): + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=index_name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = client.create_index(index) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py new file mode 100644 index 000000000000..f60bf1cb39eb --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_data_source_live.py @@ -0,0 +1,136 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest + +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator +from azure.search.documents.indexes.models import ( + SearchIndexerDataSourceConnection, + SearchIndexerDataContainer, +) +from azure.search.documents.indexes import SearchIndexerClient + + +class TestSearchClientDataSources(AzureRecordedTestCase): + def _create_data_source_connection(self, cs, name): + container = SearchIndexerDataContainer(name="searchcontainer") + data_source_connection = SearchIndexerDataSourceConnection( + name=name, type="azureblob", connection_string=cs, container=container + ) + return data_source_connection + + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_data_source(self, endpoint, **kwargs): + storage_cs = kwargs.get("search_storage_connection_string") + client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) + self._test_create_datasource(client, storage_cs) + self._test_delete_datasource(client, storage_cs) + self._test_get_datasource(client, storage_cs) + self._test_list_datasources(client, storage_cs) + self._test_create_or_update_datasource(client, storage_cs) + self._test_create_or_update_datasource_if_unchanged(client, storage_cs) + self._test_delete_datasource_if_unchanged(client, storage_cs) + self._test_delete_datasource_string_if_unchanged(client, storage_cs) + + def _test_create_datasource(self, client, storage_cs): + ds_name = "create" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + result = client.create_data_source_connection(data_source_connection) + assert result.name == ds_name + assert result.type == "azureblob" + + def _test_delete_datasource(self, client, storage_cs): + ds_name = "delete" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + client.create_data_source_connection(data_source_connection) + expected_count = len(client.get_data_source_connections()) - 1 + client.delete_data_source_connection(ds_name) + assert len(client.get_data_source_connections()) == expected_count + + def _test_get_datasource(self, client, storage_cs): + ds_name = "get" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + client.create_data_source_connection(data_source_connection) + result = client.get_data_source_connection(ds_name) + assert result.name == ds_name + + def _test_list_datasources(self, client, storage_cs): + data_source_connection1 = self._create_data_source_connection(storage_cs, "list") + data_source_connection2 = self._create_data_source_connection(storage_cs, "list2") + client.create_data_source_connection(data_source_connection1) + client.create_data_source_connection(data_source_connection2) + result = client.get_data_source_connections() + assert isinstance(result, list) + assert set(x.name for x in result).intersection(set(["list", "list2"])) == set(["list", "list2"]) + + def _test_create_or_update_datasource(self, client, storage_cs): + ds_name = "cou" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + client.create_data_source_connection(data_source_connection) + expected_count = len(client.get_data_source_connections()) + data_source_connection.description = "updated" + client.create_or_update_data_source_connection(data_source_connection) + assert len(client.get_data_source_connections()) == expected_count + result = client.get_data_source_connection(ds_name) + assert result.name == ds_name + assert result.description == "updated" + + def _test_create_or_update_datasource_if_unchanged(self, client, storage_cs): + ds_name = "couunch" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + created = client.create_data_source_connection(data_source_connection) + etag = created.e_tag + + # Now update the data source connection + data_source_connection.description = "updated" + client.create_or_update_data_source_connection(data_source_connection) + + # prepare data source connection + data_source_connection.e_tag = etag # reset to the original data source connection + data_source_connection.description = "changed" + with pytest.raises(HttpResponseError): + client.create_or_update_data_source_connection( + data_source_connection, match_condition=MatchConditions.IfNotModified + ) + + def _test_delete_datasource_if_unchanged(self, client, storage_cs): + ds_name = "delunch" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + created = client.create_data_source_connection(data_source_connection) + etag = created.e_tag + + # Now update the data source connection + data_source_connection.description = "updated" + client.create_or_update_data_source_connection(data_source_connection) + + # prepare data source connection + data_source_connection.e_tag = etag # reset to the original data source connection + with pytest.raises(HttpResponseError): + client.delete_data_source_connection(data_source_connection, match_condition=MatchConditions.IfNotModified) + + def _test_delete_datasource_string_if_unchanged(self, client, storage_cs): + ds_name = "delstrunch" + data_source_connection = self._create_data_source_connection(storage_cs, ds_name) + created = client.create_data_source_connection(data_source_connection) + etag = created.e_tag + + # Now update the data source connection + data_source_connection.description = "updated" + client.create_or_update_data_source_connection(data_source_connection) + + # prepare data source connection + data_source_connection.e_tag = etag # reset to the original data source connection + with pytest.raises(ValueError): + client.delete_data_source_connection( + data_source_connection.name, + match_condition=MatchConditions.IfNotModified, + ) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py new file mode 100644 index 000000000000..149e4d46944c --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py @@ -0,0 +1,185 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes.models import ( + AnalyzeTextOptions, + CorsOptions, + SearchIndex, + ScoringProfile, + SimpleField, + SearchFieldDataType, +) +from azure.search.documents.indexes import SearchIndexClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchIndexClient(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema=None, index_batch=None) + @recorded_by_proxy + def test_search_index_client(self, endpoint, index_name): + client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) + index_name = "hotels" + self._test_get_service_statistics(client) + self._test_list_indexes_empty(client) + self._test_create_index(client, index_name) + self._test_list_indexes(client, index_name) + self._test_get_index(client, index_name) + self._test_get_index_statistics(client, index_name) + self._test_delete_indexes_if_unchanged(client) + self._test_create_or_update_index(client) + self._test_create_or_update_indexes_if_unchanged(client) + self._test_analyze_text(client, index_name) + self._test_delete_indexes(client) + + def _test_get_service_statistics(self, client): + result = client.get_service_statistics() + assert isinstance(result, dict) + assert set(result.keys()) == {"counters", "limits"} + + def _test_list_indexes_empty(self, client): + result = client.list_indexes() + with pytest.raises(StopIteration): + next(result) + + def _test_list_indexes(self, client, index_name): + result = client.list_indexes() + first = next(result) + assert first.name == index_name + + with pytest.raises(StopIteration): + next(result) + + def _test_get_index(self, client, index_name): + result = client.get_index(index_name) + assert result.name == index_name + + def _test_get_index_statistics(self, client, index_name): + result = client.get_index_statistics(index_name) + keys = set(result.keys()) + assert "document_count" in keys + assert "storage_size" in keys + assert "vector_index_size" in keys + + def _test_create_index(self, client, index_name): + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=index_name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = client.create_index(index) + assert result.name == index_name + assert result.scoring_profiles[0].name == scoring_profile.name + assert result.cors_options.allowed_origins == cors_options.allowed_origins + assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds + + def _test_create_or_update_index(self, client): + name = "hotels-cou" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profiles = [] + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = client.create_or_update_index(index=index) + assert len(result.scoring_profiles) == 0 + assert result.cors_options.allowed_origins == cors_options.allowed_origins + assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = client.create_or_update_index(index=index) + assert result.scoring_profiles[0].name == scoring_profile.name + assert result.cors_options.allowed_origins == cors_options.allowed_origins + assert result.cors_options.max_age_in_seconds == cors_options.max_age_in_seconds + + def _test_create_or_update_indexes_if_unchanged(self, client): + # First create an index + name = "hotels-coa-unchanged" + fields = [ + {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, + {"name": "baseRate", "type": "Edm.Double"}, + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = client.create_index(index) + etag = result.e_tag + # get e tag and update + index.scoring_profiles = [] + client.create_or_update_index(index) + + index.e_tag = etag + with pytest.raises(HttpResponseError): + client.create_or_update_index(index, match_condition=MatchConditions.IfNotModified) + + def _test_analyze_text(self, client, index_name): + analyze_request = AnalyzeTextOptions(text="One's ", analyzer_name="standard.lucene") + result = client.analyze_text(index_name, analyze_request) + assert len(result.tokens) == 2 + + def _test_delete_indexes_if_unchanged(self, client): + # First create an index + name = "hotels-del-unchanged" + fields = [ + {"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}, + {"name": "baseRate", "type": "Edm.Double"}, + ] + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + index = SearchIndex( + name=name, + fields=fields, + scoring_profiles=scoring_profiles, + cors_options=cors_options, + ) + result = client.create_index(index) + etag = result.e_tag + # get e tag and update + index.scoring_profiles = [] + client.create_or_update_index(index) + + index.e_tag = etag + with pytest.raises(HttpResponseError): + client.delete_index(index, match_condition=MatchConditions.IfNotModified) + + def _test_delete_indexes(self, client): + for index in client.list_indexes(): + client.delete_index(index) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py new file mode 100644 index 000000000000..284ce51594e5 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_skillset_live.py @@ -0,0 +1,252 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.core.credentials import AzureKeyCredential +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential +from search_service_preparer import SearchEnvVarPreparer, search_decorator +from azure.search.documents.indexes.models import ( + EntityLinkingSkill, + EntityRecognitionSkill, + EntityRecognitionSkillVersion, + InputFieldMappingEntry, + OutputFieldMappingEntry, + SearchIndexerSkillset, + SentimentSkill, + SentimentSkillVersion, +) +from azure.search.documents.indexes import SearchIndexerClient + + +class TestSearchSkillset(AzureRecordedTestCase): + @pytest.mark.skip("The skills are deprecated") + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_skillset_crud(self, endpoint): + client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) + self._test_create_skillset_validation() + self._test_create_skillset(client) + self._test_get_skillset(client) + self._test_get_skillsets(client) + self._test_create_or_update_skillset(client) + self._test_create_or_update_skillset_if_unchanged(client) + self._test_create_or_update_skillset_inplace(client) + self._test_delete_skillset_if_unchanged(client) + self._test_delete_skillset(client) + + def _test_create_skillset_validation(self): + name = "test-ss-validation" + with pytest.raises(ValueError) as err: + client = SearchIndexerClient("fake_endpoint", AzureKeyCredential("fake_key")) + + s1 = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], + description="Skill Version 1", + model_version="1", + include_typeless_entities=True, + ) + + s2 = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], + skill_version=EntityRecognitionSkillVersion.LATEST, + description="Skill Version 3", + model_version="3", + include_typeless_entities=True, + ) + s3 = SentimentSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], + skill_version=SentimentSkillVersion.V1, + description="Sentiment V1", + include_opinion_mining=True, + ) + skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s3]), description="desc") + client.create_skillset(skillset) + assert "include_typeless_entities" in str(err.value) + assert "model_version" in str(err.value) + assert "include_opinion_mining" in str(err.value) + + def _test_create_skillset(self, client): + name = "test-ss-create" + s1 = EntityRecognitionSkill( + name="skill1", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS1")], + description="Skill Version 1", + include_typeless_entities=True, + ) + + s2 = EntityRecognitionSkill( + name="skill2", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizationsS2")], + skill_version=EntityRecognitionSkillVersion.LATEST, + description="Skill Version 3", + model_version="3", + ) + s3 = SentimentSkill( + name="skill3", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="score", target_name="scoreS3")], + skill_version=SentimentSkillVersion.V1, + description="Sentiment V1", + ) + + s4 = SentimentSkill( + name="skill4", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="confidenceScores", target_name="scoreS4")], + skill_version=SentimentSkillVersion.V3, + description="Sentiment V3", + include_opinion_mining=True, + ) + + s5 = EntityLinkingSkill( + name="skill5", + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="entities", target_name="entitiesS5")], + minimum_precision=0.5, + ) + + skillset = SearchIndexerSkillset(name=name, skills=list([s1, s2, s3, s4, s5]), description="desc") + + dict_skills = [skill.as_dict() for skill in skillset.skills] + skillset.skills = dict_skills + + result = client.create_skillset(skillset) + + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc" + assert result.e_tag + assert len(result.skills) == 5 + assert isinstance(result.skills[0], EntityRecognitionSkill) + assert result.skills[0].skill_version == EntityRecognitionSkillVersion.V1 + assert isinstance(result.skills[1], EntityRecognitionSkill) + assert result.skills[1].skill_version == EntityRecognitionSkillVersion.V3 + assert isinstance(result.skills[2], SentimentSkill) + assert result.skills[2].skill_version == SentimentSkillVersion.V1 + assert isinstance(result.skills[3], SentimentSkill) + assert result.skills[3].skill_version == SentimentSkillVersion.V3 + assert isinstance(result.skills[4], EntityLinkingSkill) + assert result.skills[4].minimum_precision == 0.5 + + assert len(client.get_skillsets()) == 1 + client.reset_skills(result, [x.name for x in result.skills]) + + def _test_get_skillset(self, client): + name = "test-ss-get" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") + client.create_skillset(skillset) + result = client.get_skillset(name) + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc" + assert result.e_tag + assert len(result.skills) == 1 + assert isinstance(result.skills[0], EntityRecognitionSkill) + + def _test_get_skillsets(self, client): + name1 = "test-ss-list-1" + name2 = "test-ss-list-2" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name1, skills=list([s]), description="desc1") + client.create_skillset(skillset1) + skillset2 = SearchIndexerSkillset(name=name2, skills=list([s]), description="desc2") + client.create_skillset(skillset2) + result = client.get_skillsets() + assert isinstance(result, list) + assert all(isinstance(x, SearchIndexerSkillset) for x in result) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) + + def _test_create_or_update_skillset(self, client): + name = "test-ss-create-or-update" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") + client.create_or_update_skillset(skillset1) + expected_count = len(client.get_skillsets()) + skillset2 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc2") + client.create_or_update_skillset(skillset2) + assert len(client.get_skillsets()) == expected_count + + result = client.get_skillset(name) + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc2" + + def _test_create_or_update_skillset_inplace(self, client): + name = "test-ss-create-or-update-inplace" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") + ss = client.create_or_update_skillset(skillset1) + expected_count = len(client.get_skillsets()) + skillset2 = SearchIndexerSkillset(name=name, skills=[s], description="desc2", skillset=ss) + client.create_or_update_skillset(skillset2) + assert len(client.get_skillsets()) == expected_count + + result = client.get_skillset(name) + assert isinstance(result, SearchIndexerSkillset) + assert result.name == name + assert result.description == "desc2" + + def _test_create_or_update_skillset_if_unchanged(self, client): + name = "test-ss-create-or-update-unchanged" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset1 = SearchIndexerSkillset(name=name, skills=list([s]), description="desc1") + ss = client.create_or_update_skillset(skillset1) + + ss.e_tag = "changed_etag" + + with pytest.raises(HttpResponseError): + client.create_or_update_skillset(ss, match_condition=MatchConditions.IfNotModified) + + def _test_delete_skillset_if_unchanged(self, client): + name = "test-ss-deleted-unchanged" + s = EntityRecognitionSkill( + inputs=[InputFieldMappingEntry(name="text", source="/document/content")], + outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")], + ) + + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="desc") + + result = client.create_skillset(skillset) + etag = result.e_tag + + skillset = SearchIndexerSkillset(name=name, skills=list([s]), description="updated") + updated = client.create_or_update_skillset(skillset) + updated.e_tag = etag + + with pytest.raises(HttpResponseError): + client.delete_skillset(updated, match_condition=MatchConditions.IfNotModified) + + def _test_delete_skillset(self, client): + for skillset in client.get_skillset_names(): + client.delete_skillset(skillset) diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py new file mode 100644 index 000000000000..42a4154b0f45 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_synonym_map_live.py @@ -0,0 +1,145 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest + +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes import SearchIndexClient +from azure.search.documents.indexes.models import SynonymMap +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchClientSynonymMaps(AzureRecordedTestCase): + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_synonym_map(self, endpoint): + client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) + self._test_create_synonym_map(client) + self._test_delete_synonym_map(client) + self._test_delete_synonym_map_if_unchanged(client) + self._test_get_synonym_map(client) + self._test_get_synonym_maps(client) + self._test_create_or_update_synonym_map(client) + + def _test_create_synonym_map(self, client): + expected = len(client.get_synonym_maps()) + 1 + name = "synmap-create" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + result = client.create_synonym_map(synonym_map) + assert isinstance(result, SynonymMap) + assert result.name == name + assert result.synonyms == [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + assert len(client.get_synonym_maps()) == expected + client.delete_synonym_map(name) + + def _test_delete_synonym_map(self, client): + name = "synmap-del" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + result = client.create_synonym_map(synonym_map) + expected = len(client.get_synonym_maps()) - 1 + client.delete_synonym_map(name) + assert len(client.get_synonym_maps()) == expected + + def _test_delete_synonym_map_if_unchanged(self, client): + name = "synmap-delunch" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + result = client.create_synonym_map(synonym_map) + etag = result.e_tag + + synonym_map.synonyms = "\n".join( + [ + "Washington, Wash. => WA", + ] + ) + client.create_or_update_synonym_map(synonym_map) + + result.e_tag = etag + with pytest.raises(HttpResponseError): + client.delete_synonym_map(result, match_condition=MatchConditions.IfNotModified) + client.delete_synonym_map(name) + + def _test_get_synonym_map(self, client): + expected = len(client.get_synonym_maps()) + 1 + name = "synmap-get" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + client.create_synonym_map(synonym_map) + assert len(client.get_synonym_maps()) == expected + result = client.get_synonym_map(name) + assert isinstance(result, SynonymMap) + assert result.name == name + assert result.synonyms == [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + client.delete_synonym_map(name) + + def _test_get_synonym_maps(self, client): + name1 = "synmap-list1" + name2 = "synmap-list2" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map_1 = SynonymMap(name=name1, synonyms=synonyms) + client.create_synonym_map(synonym_map_1) + synonyms = [ + "Washington, Wash. => WA", + ] + synonym_map_2 = SynonymMap(name=name2, synonyms=synonyms) + client.create_synonym_map(synonym_map_2) + result = client.get_synonym_maps() + assert isinstance(result, list) + assert all(isinstance(x, SynonymMap) for x in result) + expected = set([name1, name2]) + assert set(x.name for x in result).intersection(expected) == expected + client.delete_synonym_map(name1) + client.delete_synonym_map(name2) + + def _test_create_or_update_synonym_map(self, client): + expected = len(client.get_synonym_maps()) + 1 + name = "synmap-cou" + synonyms = [ + "USA, United States, United States of America", + "Washington, Wash. => WA", + ] + synonym_map = SynonymMap(name=name, synonyms=synonyms) + client.create_synonym_map(synonym_map) + assert len(client.get_synonym_maps()) == expected + synonym_map.synonyms = [ + "Washington, Wash. => WA", + ] + client.create_or_update_synonym_map(synonym_map) + assert len(client.get_synonym_maps()) == expected + result = client.get_synonym_map(name) + assert isinstance(result, SynonymMap) + assert result.name == name + assert result.synonyms == [ + "Washington, Wash. => WA", + ] + client.delete_synonym_map(name) diff --git a/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py b/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py new file mode 100644 index 000000000000..5dc6daacdab2 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_search_indexer_client_live.py @@ -0,0 +1,158 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import time + +import pytest +from azure.core import MatchConditions +from azure.core.exceptions import HttpResponseError +from azure.search.documents.indexes import SearchIndexClient, SearchIndexerClient +from azure.search.documents.indexes.models import ( + SearchIndex, + SearchIndexer, + SearchIndexerDataContainer, + SearchIndexerDataSourceConnection, +) +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, get_credential + +from search_service_preparer import SearchEnvVarPreparer, search_decorator + + +class TestSearchIndexerClientTest(AzureRecordedTestCase): + @pytest.mark.skip("fails because connection string of storage is disabled") + @SearchEnvVarPreparer() + @search_decorator(schema="hotel_schema.json", index_batch="hotel_small.json") + @recorded_by_proxy + def test_search_indexers(self, endpoint, **kwargs): + storage_cs = kwargs.get("search_storage_connection_string") + container_name = kwargs.get("search_storage_container_name") + client = SearchIndexerClient(endpoint, get_credential(), retry_backoff_factor=60) + index_client = SearchIndexClient(endpoint, get_credential(), retry_backoff_factor=60) + self._test_create_indexer(client, index_client, storage_cs, container_name) + self._test_delete_indexer(client, index_client, storage_cs, container_name) + self._test_get_indexer(client, index_client, storage_cs, container_name) + self._test_list_indexer(client, index_client, storage_cs, container_name) + self._test_create_or_update_indexer(client, index_client, storage_cs, container_name) + self._test_reset_indexer(client, index_client, storage_cs, container_name) + self._test_run_indexer(client, index_client, storage_cs, container_name) + self._test_get_indexer_status(client, index_client, storage_cs, container_name) + self._test_create_or_update_indexer_if_unchanged(client, index_client, storage_cs, container_name) + self._test_delete_indexer_if_unchanged(client, index_client, storage_cs, container_name) + + def _prepare_indexer(self, client, index_client, storage_cs, name, container_name): + data_source_connection = SearchIndexerDataSourceConnection( + name=f"{name}-ds", + type="azureblob", + connection_string=storage_cs, + container=SearchIndexerDataContainer(name=container_name), + ) + ds = client.create_data_source_connection(data_source_connection) + + fields = [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False}] + index = SearchIndex(name=f"{name}-hotels", fields=fields) + ind = index_client.create_index(index) + return SearchIndexer(name=name, data_source_name=ds.name, target_index_name=ind.name) + + def _test_create_indexer(self, client, index_client, storage_cs, container_name): + name = "create" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + result = client.create_indexer(indexer) + assert result.name == name + assert result.target_index_name == f"{name}-hotels" + assert result.data_source_name == f"{name}-ds" + + def _test_delete_indexer(self, client, index_client, storage_cs, container_name): + name = "delete" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + client.create_indexer(indexer) + expected = len(client.get_indexers()) - 1 + client.delete_indexer(name) + assert len(client.get_indexers()) == expected + + def _test_get_indexer(self, client, index_client, storage_cs, container_name): + name = "get" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + client.create_indexer(indexer) + result = client.get_indexer(name) + assert result.name == name + + def _test_list_indexer(self, client, index_client, storage_cs, container_name): + name1 = "list1" + name2 = "list2" + indexer1 = self._prepare_indexer(client, index_client, storage_cs, name1, container_name) + indexer2 = self._prepare_indexer(client, index_client, storage_cs, name2, container_name) + client.create_indexer(indexer1) + client.create_indexer(indexer2) + result = client.get_indexers() + assert isinstance(result, list) + assert set(x.name for x in result).intersection([name1, name2]) == set([name1, name2]) + + def _test_create_or_update_indexer(self, client, index_client, storage_cs, container_name): + name = "cou" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + client.create_indexer(indexer) + expected = len(client.get_indexers()) + if self.is_live: + time.sleep(10) + indexer.description = "updated" + client.create_or_update_indexer(indexer) + assert len(client.get_indexers()) == expected + result = client.get_indexer(name) + assert result.name == name + assert result.description == "updated" + + def _test_reset_indexer(self, client, index_client, storage_cs, container_name): + name = "reset" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + client.create_indexer(indexer) + if self.is_live: + time.sleep(10) + client.reset_indexer(name) + assert (client.get_indexer_status(name)).last_result.status.lower() in ( + "inprogress", + "reset", + ) + + def _test_run_indexer(self, client, index_client, storage_cs, container_name): + name = "run" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + client.create_indexer(indexer) + client.run_indexer(name) + assert (client.get_indexer_status(name)).status == "running" + + def _test_get_indexer_status(self, client, index_client, storage_cs, container_name): + name = "get-status" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + client.create_indexer(indexer) + status = client.get_indexer_status(name) + assert status.status is not None + + def _test_create_or_update_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): + name = "couunch" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + created = client.create_indexer(indexer) + etag = created.e_tag + if self.is_live: + time.sleep(10) + indexer.description = "updated" + client.create_or_update_indexer(indexer) + + indexer.e_tag = etag + with pytest.raises(HttpResponseError): + client.create_or_update_indexer(indexer, match_condition=MatchConditions.IfNotModified) + + def _test_delete_indexer_if_unchanged(self, client, index_client, storage_cs, container_name): + name = "delunch" + indexer = self._prepare_indexer(client, index_client, storage_cs, name, container_name) + result = client.create_indexer(indexer) + etag = result.e_tag + if self.is_live: + time.sleep(10) + indexer.description = "updated" + client.create_or_update_indexer(indexer) + + indexer.e_tag = etag + with pytest.raises(HttpResponseError): + client.delete_indexer(indexer, match_condition=MatchConditions.IfNotModified) diff --git a/sdk/search/azure-search-documents/tests/test_serialization.py b/sdk/search/azure-search-documents/tests/test_serialization.py new file mode 100644 index 000000000000..09a5f04caf32 --- /dev/null +++ b/sdk/search/azure-search-documents/tests/test_serialization.py @@ -0,0 +1,108 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from azure.search.documents.indexes.models import ( + SearchIndex, + SearchIndexerSkillset, + SearchFieldDataType, + SimpleField, + SearchableField, + ComplexField, + ScoringProfile, + CorsOptions, + CognitiveServicesAccountKey, + InputFieldMappingEntry, + OutputFieldMappingEntry, + SearchIndexerSkillset, + SplitSkill, + TextSplitMode, +) + + +def test_serialize_search_index(): + new_index_name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + SearchableField(name="hotelName", type=SearchFieldDataType.String), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + SimpleField(name="state", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex( + name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options + ) + search_index_serialized = index.serialize() + search_index = SearchIndex.deserialize(search_index_serialized) + assert search_index + + +def test_serialize_search_indexer_skillset(): + COGNITIVE_KEY = ... + COGNITIVE_DESCRIPTION = ... + + cognitive_services_account = CognitiveServicesAccountKey(key=COGNITIVE_KEY, description=COGNITIVE_DESCRIPTION) + + inputs = [InputFieldMappingEntry(name="text", source="/document/content")] + + outputs = [OutputFieldMappingEntry(name="textItems", target_name="pages")] + + split_skill = SplitSkill( + name="SplitSkill", + inputs=inputs, + outputs=outputs, + context="/document", + text_split_mode=TextSplitMode.PAGES, + maximum_page_length=5000, + ) + + skills = [split_skill] + skillset = SearchIndexerSkillset( + name="Skillset", skills=skills, cognitive_services_account=cognitive_services_account + ) + + serialized_skillset = skillset.serialize() + skillset = SearchIndexerSkillset.deserialize(serialized_skillset) + assert skillset + + +def test_serialize_search_index_dict(): + new_index_name = "hotels" + fields = [ + SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="baseRate", type=SearchFieldDataType.Double), + SearchableField(name="description", type=SearchFieldDataType.String, collection=True), + SearchableField(name="hotelName", type=SearchFieldDataType.String), + ComplexField( + name="address", + fields=[ + SimpleField(name="streetAddress", type=SearchFieldDataType.String), + SimpleField(name="city", type=SearchFieldDataType.String), + SimpleField(name="state", type=SearchFieldDataType.String), + ], + collection=True, + ), + ] + cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) + scoring_profile = ScoringProfile(name="MyProfile") + scoring_profiles = [] + scoring_profiles.append(scoring_profile) + index = SearchIndex( + name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options + ) + search_index_serialized_dict = index.as_dict() + search_index = SearchIndex.from_dict(search_index_serialized_dict) + assert search_index From fd9b5fb7aa796d6f848d0e63e2718e60969fb456 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 24 Oct 2025 16:30:35 -0700 Subject: [PATCH 06/40] updates --- .../samples/batch_upload.py | 10 --- .../samples/simple_query.py | 66 ------------------- 2 files changed, 76 deletions(-) delete mode 100644 sdk/search/azure-search-documents/samples/batch_upload.py delete mode 100644 sdk/search/azure-search-documents/samples/simple_query.py diff --git a/sdk/search/azure-search-documents/samples/batch_upload.py b/sdk/search/azure-search-documents/samples/batch_upload.py deleted file mode 100644 index da4f83564959..000000000000 --- a/sdk/search/azure-search-documents/samples/batch_upload.py +++ /dev/null @@ -1,10 +0,0 @@ -from azure.search.documents import SearchClient -from azure.identity import AzureCliCredential - -client = SearchClient( - endpoint="https://vector-search-test.search.windows.net", - index_name="batch-test", - credential=AzureCliCredential(), -) -documents = [{"id": str(i), "content": " " * 10000} for i in range(10000)] -client.upload_documents(documents=documents) diff --git a/sdk/search/azure-search-documents/samples/simple_query.py b/sdk/search/azure-search-documents/samples/simple_query.py deleted file mode 100644 index 3fce6b4ba2d0..000000000000 --- a/sdk/search/azure-search-documents/samples/simple_query.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -""" -FILE: sample_simple_query.py -DESCRIPTION: - This sample demonstrates how to get search results from a basic search text - from an Azure Search index. -USAGE: - python sample_simple_query.py - - Set the environment variables with your own values before running the sample: - 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service - 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") - 3) AZURE_SEARCH_API_KEY - your search API key -""" - -import os - -service_endpoint = "https://gh-issue-test.search.windows.net" -index_name = "document-index3-python" - - -def simple_text_query(): - # [START simple_query] - from azure.identity import AzureCliCredential - from azure.search.documents import SearchClient - from azure.search.documents.indexes.models import ( - SemanticConfiguration, - SemanticPrioritizedFields, - SemanticField, - ) - - search_client = SearchClient(service_endpoint, index_name, AzureCliCredential()) - # semantic_config = SemanticConfiguration( - # name="semantic_config_name", - # prioritized_fields=[ - # SemanticPrioritizedFields( - # title_field=SemanticField(field_name="Title"), - # content_fields=[ - # SemanticField(field_name="content") - # ] - # ) - # ] - # ) - - results = search_client.search( - search_text="luxury", - query_type="semantic", - debug="all", - semantic_configuration_name="document-semantic-config", - ) - - print("Docs containing 'PersonalizerClient' in the name (or other fields):") - for result in results: - print(" Title: {} (chunk {})".format(result["Title"], result["chunk"])) - # [END simple_query] - - -if __name__ == "__main__": - simple_text_query() From 7752a3694d7f27f04dce2bbcc9883a2c2fa65894 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 24 Oct 2025 17:07:33 -0700 Subject: [PATCH 07/40] update --- .../search/documents/indexes/models/_patch.py | 42 +++++++++++++------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index dbd6cee799d0..8b71cd007245 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -22,23 +22,38 @@ from ._enums import ( LexicalAnalyzerName, IndexerPermissionOption, - SearchFieldDataType, + SearchFieldDataType as _SearchFieldDataType, PermissionFilter, VectorEncodingFormat, ) -String = "Edm.String" -Int32 = "Edm.Int32" -Int64 = "Edm.Int64" -Single = "Edm.Single" -Double = "Edm.Double" -Boolean = "Edm.Boolean" -DateTimeOffset = "Edm.DateTimeOffset" -GeographyPoint = "Edm.GeographyPoint" -ComplexType = "Edm.ComplexType" +# Re-export SearchFieldDataType and add Collection helper +SearchFieldDataType = _SearchFieldDataType +# Add Collection method to SearchFieldDataType enum +def _collection_helper(typ) -> str: + """Helper function to create a collection type string. + + :param typ: The type to wrap in a collection. Can be a string or an enum value. + :return: A collection type string. + """ + # If typ is an enum, get its value; otherwise use it as-is + if hasattr(typ, 'value'): + typ = typ.value + return "Collection({})".format(typ) -def Collection(typ: str) -> str: +# Monkey-patch the Collection method onto the enum class +SearchFieldDataType.Collection = staticmethod(_collection_helper) + +def Collection(typ) -> str: + """Helper function to create a collection type string. + + :param typ: The type to wrap in a collection. Can be a string or an enum value. + :return: A collection type string. + """ + # If typ is an enum, get its value; otherwise use it as-is + if hasattr(typ, 'value'): + typ = typ.value return "Collection({})".format(typ) @@ -450,7 +465,7 @@ def SearchableField( :return: The search field object. :rtype: SearchField """ - typ = Collection(String) if collection else String + typ = Collection(SearchFieldDataType.String) if collection else SearchFieldDataType.String result: Dict[str, Any] = { "name": name, "type": typ, @@ -491,7 +506,7 @@ def ComplexField( :return: The search field object. :rtype: SearchField """ - typ = Collection(ComplexType) if collection else ComplexType + typ = Collection(SearchFieldDataType.ComplexType) if collection else SearchFieldDataType.ComplexType result: Dict[str, Any] = {"name": name, "type": typ, "fields": fields} return _SearchField(**result) @@ -574,6 +589,7 @@ def __init__( __all__: list[str] = [ "SearchField", + "SearchFieldDataType", "SimpleField", "SearchableField", "ComplexField", From fda92367929a708af7c46f2d292185a55eb77577 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 09:49:34 -0700 Subject: [PATCH 08/40] update --- .../documents/indexes/_operations/_patch.py | 97 ++++++++++++++++++- .../indexes/aio/_operations/_patch.py | 89 ++++++++++++++++- 2 files changed, 184 insertions(+), 2 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 87676c65a8f0..7e39bc4a8f2d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -7,9 +7,104 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Iterator, cast, List, Sequence +from azure.core.paging import ItemPaged +from azure.core.tracing.decorator import distributed_trace -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +from ._operations import ( + _SearchIndexClientOperationsMixin as _SearchIndexClientOperationsMixinGenerated, + _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, +) + +class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexClient.""" + + @distributed_trace + def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: + """Lists the names of all indexes available for a search service. + + :return: An iterator like instance of index names + :rtype: ~azure.core.paging.ItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(ItemPaged[str], names) + + @distributed_trace + def get_synonym_map_names(self, **kwargs: Any) -> List[str]: + """Lists the names of all synonym maps available for a search service. + + :return: List of synonym maps + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self.get_synonym_maps(**kwargs) + assert result.synonym_maps is not None # Hint for mypy + return [x.name for x in result.synonym_maps] + + @distributed_trace + def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: + """List the alias names in an Azure Search service. + + :return: List of alias names + :rtype: ~azure.core.paging.ItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. + + """ + names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(ItemPaged[str], names) + + +class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexerClient.""" + @distributed_trace + def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: + """Lists all indexer names available for a search service. + + :return: List of all the SearchIndexers. + :rtype: list[str] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_indexers_operations.py + :start-after: [START list_indexer] + :end-before: [END list_indexer] + :language: python + :dedent: 4 + :caption: List all the SearchIndexers + """ + kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) + result = self.list_indexers(**kwargs) + assert result.indexers is not None # Hint for mypy + return [x.name for x in result.indexers] + + @distributed_trace + def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: + """Lists all data source connection names available for a search service. + + :return: List of all the data source connection names. + :rtype: list[str] + + """ + result = self.list_data_sources(**kwargs) + assert result.data_sources is not None # Hint for mypy + return [x.name for x in result.data_sources] + + @distributed_trace + def get_skillset_names(self, **kwargs: Any) -> List[str]: + """List the SearchIndexerSkillset names in an Azure Search service. + + :return: List of SearchIndexerSkillset names + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. + + """ + result = self.list_skillsets(**kwargs) + assert result.skillsets is not None # Hint for mypy + return [x.name for x in result.skillsets] + +__all__: list[str] = ["_SearchIndexClientOperationsMixin", "_SearchIndexerClientOperationsMixin"] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 87676c65a8f0..28527e921deb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -7,9 +7,96 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, AsyncIterator, cast, List, Sequence +from azure.core.async_paging import AsyncItemPaged +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +from ._operations import ( + _SearchIndexClientOperationsMixin as _SearchIndexClientOperationsMixinGenerated, + _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, +) + + +class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexClient (async).""" + + @distributed_trace + def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: + """Lists the names of all indexes available for a search service. + + :return: An async iterator like instance of index names + :rtype: ~azure.core.async_paging.AsyncItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(AsyncItemPaged[str], names) + + @distributed_trace_async + async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: + """Lists the names of all synonym maps available for a search service. + + :return: An async iterator of synonym map names + :rtype: AsyncIterator[str] + :raises ~azure.core.exceptions.HttpResponseError: + """ + # Call the base get_synonym_maps method with select='name' to only retrieve names + result = await self.get_synonym_maps(select="name", **kwargs) + # Extract and yield just the names from the synonym_maps list + return [x.name for x in result.synonym_maps] + + @distributed_trace + def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: + """List the alias names in an Azure Search service. + + :return: List of alias names + :rtype: ~azure.core.async_paging.AsyncItemPaged[str] + :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. + """ + names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) + return cast(AsyncItemPaged[str], names) + + +class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): + """Custom operations mixin for SearchIndexerClient (async).""" + @distributed_trace_async + async def get_indexer_names(self, **kwargs) -> Sequence[str]: + """Lists all indexer names available for a search service. + + :return: List of all the SearchIndexer names. + :rtype: list[str] + """ + result = await self.list_indexers(**kwargs) + assert result.indexers is not None # Hint for mypy + return [x.name for x in result.indexers] + + @distributed_trace_async + async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: + """Lists all data source connection names available for a search service. + + :return: List of all the data source connection names. + :rtype: list[str] + + """ + result = await self.list_data_sources(**kwargs) + assert result.data_sources is not None # Hint for mypy + return [x.name for x in result.data_sources] + + @distributed_trace_async + async def get_skillset_names(self, **kwargs) -> Sequence[str]: + """List the SearchIndexerSkillset names in an Azure Search service. + + :return: List of SearchIndexerSkillset names + :rtype: list[str] + :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. + + """ + result = await self.list_skillsets(**kwargs) + assert result.skillsets is not None # Hint for mypy + return [x.name for x in result.skillsets] + +__all__: list[str] = ["_SearchIndexClientOperationsMixin", "_SearchIndexerClientOperationsMixin"] # Add all objects you want publicly available to users at this package level def patch_sdk(): From b7d45b82b526cd96b5910d79fa5e69e842a2253a Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 09:49:42 -0700 Subject: [PATCH 09/40] update --- .../samples/sample_vector_search.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sdk/search/azure-search-documents/samples/sample_vector_search.py b/sdk/search/azure-search-documents/samples/sample_vector_search.py index b7bfbc31d44a..8b490764ff68 100644 --- a/sdk/search/azure-search-documents/samples/sample_vector_search.py +++ b/sdk/search/azure-search-documents/samples/sample_vector_search.py @@ -61,24 +61,24 @@ def get_hotel_index(name: str): ) fields = [ - SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True), + SimpleField(name="hotelId", type=SearchFieldDataType.STRING, key=True), SearchableField( name="hotelName", - type=SearchFieldDataType.String, + type=SearchFieldDataType.SINGLE, sortable=True, filterable=True, ), - SearchableField(name="description", type=SearchFieldDataType.String), + SearchableField(name="description", type=SearchFieldDataType.STRING), SearchField( name="descriptionVector", - type=SearchFieldDataType.Collection(SearchFieldDataType.Single), + type=SearchFieldDataType.Collection(SearchFieldDataType.SINGLE), searchable=True, vector_search_dimensions=1536, vector_search_profile_name="my-vector-config", ), SearchableField( name="category", - type=SearchFieldDataType.String, + type=SearchFieldDataType.STRING, sortable=True, filterable=True, facetable=True, From 4e6d35fdc3331e47afbdff45f6095bdf0c1df93b Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 10:42:36 -0700 Subject: [PATCH 10/40] update --- .../search/documents/_operations/_patch.py | 122 ++++++++++++++++- .../documents/aio/_operations/_patch.py | 123 +++++++++++++++++- .../search/documents/indexes/models/_patch.py | 2 +- .../azure/search/documents/models/_patch.py | 91 ++++++++++++- 4 files changed, 334 insertions(+), 4 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 87676c65a8f0..4b730d1b4aec 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -7,9 +7,129 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Dict, List, cast +from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated +from .. import models as _models -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + +class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): + """SearchClient operations mixin customizations.""" + + def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Upload documents to the Azure search index. + + An upload action is similar to an "upsert" where the document will be + inserted if it is new and updated/replaced if it exists. All fields are + replaced in the update case. + + :param documents: A list of documents to upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_crud_operations.py + :start-after: [START upload_document] + :end-before: [END upload_document] + :language: python + :dedent: 4 + :caption: Upload new documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_upload_actions(documents) + + result = self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Delete documents from the Azure search index. + + Delete removes the specified documents from the index. Any field you + specify in a delete operation, other than the key field, will be ignored. + If you want to remove a field from a document, use merge instead and + set the field explicitly to None. + + :param documents: A list of documents to delete. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_crud_operations.py + :start-after: [START delete_document] + :end-before: [END delete_document] + :language: python + :dedent: 4 + :caption: Delete documents from an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_delete_actions(documents) + + result = self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge documents in the Azure search index. + + Merge updates an existing document with the specified fields. If the + document doesn't exist, the merge will fail. Any field you specify in + a merge will replace the existing field in the document. This also + applies to collections of primitive and complex types. + + :param documents: A list of documents to merge. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_crud_operations.py + :start-after: [START merge_document] + :end-before: [END merge_document] + :language: python + :dedent: 4 + :caption: Merge documents in an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_actions(documents) + + result = self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge or upload documents to the Azure search index. + + Merge or upload behaves like merge if a document with the given key + already exists in the index. If the document does not exist, it behaves + like upload with a new document. + + :param documents: A list of documents to merge or upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_crud_operations.py + :start-after: [START merge_or_upload_document] + :end-before: [END merge_or_upload_document] + :language: python + :dedent: 4 + :caption: Merge or upload documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_or_upload_actions(documents) + + result = self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + +__all__: list[str] = [ + "_SearchClientOperationsMixin", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 87676c65a8f0..440515b9bedf 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -7,9 +7,129 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Dict, List, cast +from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated +from ... import models as _models -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + +class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): + """Async SearchClient operations mixin customizations.""" + + async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Upload documents to the Azure search index. + + An upload action is similar to an "upsert" where the document will be + inserted if it is new and updated/replaced if it exists. All fields are + replaced in the update case. + + :param documents: A list of documents to upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py + :start-after: [START upload_document] + :end-before: [END upload_document] + :language: python + :dedent: 4 + :caption: Upload new documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_upload_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Delete documents from the Azure search index. + + Delete removes the specified documents from the index. Any field you + specify in a delete operation, other than the key field, will be ignored. + If you want to remove a field from a document, use merge instead and + set the field explicitly to None. + + :param documents: A list of documents to delete. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py + :start-after: [START delete_document] + :end-before: [END delete_document] + :language: python + :dedent: 4 + :caption: Delete documents from an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_delete_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge documents in the Azure search index. + + Merge updates an existing document with the specified fields. If the + document doesn't exist, the merge will fail. Any field you specify in + a merge will replace the existing field in the document. This also + applies to collections of primitive and complex types. + + :param documents: A list of documents to merge. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py + :start-after: [START merge_document] + :end-before: [END merge_document] + :language: python + :dedent: 4 + :caption: Merge documents in an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: + """Merge or upload documents to the Azure search index. + + Merge or upload behaves like merge if a document with the given key + already exists in the index. If the document does not exist, it behaves + like upload with a new document. + + :param documents: A list of documents to merge or upload. + :type documents: list[dict] + :return: List of IndexingResult + :rtype: list[~azure.search.documents.models.IndexingResult] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_crud_operations_async.py + :start-after: [START merge_or_upload_document] + :end-before: [END merge_or_upload_document] + :language: python + :dedent: 4 + :caption: Merge or upload documents to an index + """ + batch = _models.IndexDocumentsBatch() + batch.add_merge_or_upload_actions(documents) + + result = await self.index_documents(batch, **kwargs) + return cast(List[_models.IndexingResult], result.results) + + +__all__: list[str] = [ + "_SearchClientOperationsMixin", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -19,3 +139,4 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ + diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index 8b71cd007245..7fdb3964b0c0 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -506,7 +506,7 @@ def ComplexField( :return: The search field object. :rtype: SearchField """ - typ = Collection(SearchFieldDataType.ComplexType) if collection else SearchFieldDataType.ComplexType + typ = Collection(SearchFieldDataType.COMPLEX) if collection else SearchFieldDataType.COMPLEX result: Dict[str, Any] = {"name": name, "type": typ, "fields": fields} return _SearchField(**result) diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py index 87676c65a8f0..a98bbf2cbaf3 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py @@ -7,9 +7,98 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Dict, List +from ._models import IndexDocumentsBatch as IndexDocumentsBatchGenerated +from ._models import IndexAction +from ._enums import IndexActionType -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + +class IndexDocumentsBatch(IndexDocumentsBatchGenerated): + """Contains a batch of document write actions to send to the index.""" + + def add_upload_actions(self, documents: List[Dict[str, Any]]) -> None: + """Add upload actions for documents. + + An upload action is similar to an "upsert" where the document will be + inserted if it is new and updated/replaced if it exists. All fields are + replaced in the update case. + + :param documents: A list of documents to upload. + :type documents: list[dict[str, Any]] + """ + if not hasattr(self, "actions") or self.actions is None: + self.actions = [] + + for doc in documents: + # Create a mapping that includes both the action type and document fields + action_dict = {"@search.action": IndexActionType.UPLOAD} + action_dict.update(doc) + action = IndexAction(action_dict) + self.actions.append(action) + + def add_delete_actions(self, documents: List[Dict[str, Any]]) -> None: + """Add delete actions for documents. + + Delete removes the specified documents from the index. + + :param documents: A list of documents to delete. + :type documents: list[dict[str, Any]] + """ + if not hasattr(self, "actions") or self.actions is None: + self.actions = [] + + for doc in documents: + # Create a mapping that includes both the action type and document fields + action_dict = {"@search.action": IndexActionType.DELETE} + action_dict.update(doc) + action = IndexAction(action_dict) + self.actions.append(action) + + def add_merge_actions(self, documents: List[Dict[str, Any]]) -> None: + """Add merge actions for documents. + + Merge updates an existing document with the specified fields. If the document + doesn't exist, the merge will fail. Any field you specify in a merge will + replace the existing field in the document. + + :param documents: A list of documents to merge. + :type documents: list[dict[str, Any]] + """ + if not hasattr(self, "actions") or self.actions is None: + self.actions = [] + + for doc in documents: + # Create a mapping that includes both the action type and document fields + action_dict = {"@search.action": IndexActionType.MERGE} + action_dict.update(doc) + action = IndexAction(action_dict) + self.actions.append(action) + + def add_merge_or_upload_actions(self, documents: List[Dict[str, Any]]) -> None: + """Add merge or upload actions for documents. + + Merge or upload behaves like merge if a document with the given key already + exists in the index. If the document does not exist, it behaves like upload + with a new document. + + :param documents: A list of documents to merge or upload. + :type documents: list[dict[str, Any]] + """ + if not hasattr(self, "actions") or self.actions is None: + self.actions = [] + + for doc in documents: + # Create a mapping that includes both the action type and document fields + action_dict = {"@search.action": IndexActionType.MERGE_OR_UPLOAD} + action_dict.update(doc) + action = IndexAction(action_dict) + self.actions.append(action) + + +__all__: list[str] = [ + "IndexDocumentsBatch", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): From 6d791af60895bdeb149cbeb2d064a06ed92aea34 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 10:55:46 -0700 Subject: [PATCH 11/40] update --- .../azure/search/documents/_operations/_patch.py | 2 +- .../azure/search/documents/aio/_operations/_patch.py | 3 +-- .../search/documents/indexes/_operations/_patch.py | 12 +++++++++--- .../documents/indexes/aio/_operations/_patch.py | 11 ++++++++--- .../azure/search/documents/indexes/models/_patch.py | 11 +++++++---- 5 files changed, 26 insertions(+), 13 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 4b730d1b4aec..f878bf789efc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -46,7 +46,7 @@ def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Delete documents from the Azure search index. - Delete removes the specified documents from the index. Any field you + Delete removes the specified documents from the index. Any field you specify in a delete operation, other than the key field, will be ignored. If you want to remove a field from a document, use merge instead and set the field explicitly to None. diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 440515b9bedf..1a53b3bfbcba 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -46,7 +46,7 @@ async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Delete documents from the Azure search index. - Delete removes the specified documents from the index. Any field you + Delete removes the specified documents from the index. Any field you specify in a delete operation, other than the key field, will be ignored. If you want to remove a field from a document, use merge instead and set the field explicitly to None. @@ -139,4 +139,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 7e39bc4a8f2d..a2be8396d5ff 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -17,6 +17,7 @@ _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, ) + class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexClient.""" @@ -58,6 +59,7 @@ def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexerClient.""" + @distributed_trace def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: """Lists all indexer names available for a search service. @@ -78,7 +80,7 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: result = self.list_indexers(**kwargs) assert result.indexers is not None # Hint for mypy return [x.name for x in result.indexers] - + @distributed_trace def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: """Lists all data source connection names available for a search service. @@ -90,7 +92,7 @@ def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: result = self.list_data_sources(**kwargs) assert result.data_sources is not None # Hint for mypy return [x.name for x in result.data_sources] - + @distributed_trace def get_skillset_names(self, **kwargs: Any) -> List[str]: """List the SearchIndexerSkillset names in an Azure Search service. @@ -104,7 +106,11 @@ def get_skillset_names(self, **kwargs: Any) -> List[str]: assert result.skillsets is not None # Hint for mypy return [x.name for x in result.skillsets] -__all__: list[str] = ["_SearchIndexClientOperationsMixin", "_SearchIndexerClientOperationsMixin"] # Add all objects you want publicly available to users at this package level + +__all__: list[str] = [ + "_SearchIndexClientOperationsMixin", + "_SearchIndexerClientOperationsMixin", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 28527e921deb..899250840160 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -60,6 +60,7 @@ def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexerClient (async).""" + @distributed_trace_async async def get_indexer_names(self, **kwargs) -> Sequence[str]: """Lists all indexer names available for a search service. @@ -70,7 +71,7 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: result = await self.list_indexers(**kwargs) assert result.indexers is not None # Hint for mypy return [x.name for x in result.indexers] - + @distributed_trace_async async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: """Lists all data source connection names available for a search service. @@ -82,7 +83,7 @@ async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: result = await self.list_data_sources(**kwargs) assert result.data_sources is not None # Hint for mypy return [x.name for x in result.data_sources] - + @distributed_trace_async async def get_skillset_names(self, **kwargs) -> Sequence[str]: """List the SearchIndexerSkillset names in an Azure Search service. @@ -96,7 +97,11 @@ async def get_skillset_names(self, **kwargs) -> Sequence[str]: assert result.skillsets is not None # Hint for mypy return [x.name for x in result.skillsets] -__all__: list[str] = ["_SearchIndexClientOperationsMixin", "_SearchIndexerClientOperationsMixin"] # Add all objects you want publicly available to users at this package level + +__all__: list[str] = [ + "_SearchIndexClientOperationsMixin", + "_SearchIndexerClientOperationsMixin", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index 7fdb3964b0c0..46021bd0f65e 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -30,29 +30,32 @@ # Re-export SearchFieldDataType and add Collection helper SearchFieldDataType = _SearchFieldDataType + # Add Collection method to SearchFieldDataType enum def _collection_helper(typ) -> str: """Helper function to create a collection type string. - + :param typ: The type to wrap in a collection. Can be a string or an enum value. :return: A collection type string. """ # If typ is an enum, get its value; otherwise use it as-is - if hasattr(typ, 'value'): + if hasattr(typ, "value"): typ = typ.value return "Collection({})".format(typ) + # Monkey-patch the Collection method onto the enum class SearchFieldDataType.Collection = staticmethod(_collection_helper) + def Collection(typ) -> str: """Helper function to create a collection type string. - + :param typ: The type to wrap in a collection. Can be a string or an enum value. :return: A collection type string. """ # If typ is an enum, get its value; otherwise use it as-is - if hasattr(typ, 'value'): + if hasattr(typ, "value"): typ = typ.value return "Collection({})".format(typ) From fa60e1767d3ccd40ca4f55d25fbf09d26e1c2b74 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 11:14:46 -0700 Subject: [PATCH 12/40] update --- .../azure/search/documents/models/_models.py | 53 ++++--------------- 1 file changed, 9 insertions(+), 44 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index 49ef5bd5d8d6..d76287449034 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -724,52 +724,42 @@ class SearchDocumentsResult(_Model): ~azure.search.documents.models.SemanticQueryRewritesResultType """ - count: Optional[int] = rest_field(name="@odata.count", visibility=["read", "create", "update", "delete", "query"]) + count: Optional[int] = rest_field(name="@odata.count", visibility=["read"]) """The total count of results found by the search operation, or null if the count was not requested. If present, the count may be greater than the number of results in this response. This can happen if you use the $top or $skip parameters, or if the query can't return all the requested documents in a single response.""" - coverage: Optional[float] = rest_field( - name="@search.coverage", visibility=["read", "create", "update", "delete", "query"] - ) + coverage: Optional[float] = rest_field(name="@search.coverage", visibility=["read"]) """A value indicating the percentage of the index that was included in the query, or null if minimumCoverage was not specified in the request.""" - facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field( - name="@search.facets", visibility=["read", "create", "update", "delete", "query"] - ) + facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field(name="@search.facets", visibility=["read"]) """The facet query results for the search operation, organized as a collection of buckets for each faceted field; null if the query did not include any facet expressions.""" - answers: Optional[list["_models.QueryAnswerResult"]] = rest_field( - name="@search.answers", visibility=["read", "create", "update", "delete", "query"] - ) + answers: Optional[list["_models.QueryAnswerResult"]] = rest_field(name="@search.answers", visibility=["read"]) """The answers query results for the search operation; null if the answers query parameter was not specified or set to 'none'.""" debug_info: Optional["_models.DebugInfo"] = rest_field(name="@search.debug", visibility=["read"]) """Debug information that applies to the search results as a whole.""" next_page_parameters: Optional["_models.SearchRequest"] = rest_field( - name="@search.nextPageParameters", visibility=["read", "create", "update", "delete", "query"] + name="@search.nextPageParameters", visibility=["read"] ) """Continuation JSON payload returned when the query can't return all the requested results in a single response. You can use this JSON along with @odata.nextLink to formulate another POST Search request to get the next part of the search response.""" - results: list["_models.SearchResult"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) + results: list["_models.SearchResult"] = rest_field(name="value", visibility=["read"]) """The sequence of results returned by the query. Required.""" - next_link: Optional[str] = rest_field( - name="@odata.nextLink", visibility=["read", "create", "update", "delete", "query"] - ) + next_link: Optional[str] = rest_field(name="@odata.nextLink", visibility=["read"]) """Continuation URL returned when the query can't return all the requested results in a single response. You can use this URL to formulate another GET or POST Search request to get the next part of the search response. Make sure to use the same verb (GET or POST) as the request that produced this response.""" semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = rest_field( - name="@search.semanticPartialResponseReason", visibility=["read", "create", "update", "delete", "query"] + name="@search.semanticPartialResponseReason", visibility=["read"] ) """Reason that a partial response was returned for a semantic ranking request. Known values are: \"maxWaitExceeded\", \"capacityOverloaded\", and \"transient\".""" semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = rest_field( - name="@search.semanticPartialResponseType", visibility=["read", "create", "update", "delete", "query"] + name="@search.semanticPartialResponseType", visibility=["read"] ) """Type of partial response that was returned for a semantic ranking request. Known values are: \"baseResults\" and \"rerankedResults\".""" @@ -778,31 +768,6 @@ class SearchDocumentsResult(_Model): ) """Type of query rewrite that was used to retrieve documents. \"originalQueryOnly\"""" - @overload - def __init__( - self, - *, - results: list["_models.SearchResult"], - count: Optional[int] = None, - coverage: Optional[float] = None, - facets: Optional[dict[str, list["_models.FacetResult"]]] = None, - answers: Optional[list["_models.QueryAnswerResult"]] = None, - next_page_parameters: Optional["_models.SearchRequest"] = None, - next_link: Optional[str] = None, - semantic_partial_response_reason: Optional[Union[str, "_models.SemanticErrorReason"]] = None, - semantic_partial_response_type: Optional[Union[str, "_models.SemanticSearchResultsType"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class SearchRequest(_Model): """Parameters for filtering, sorting, faceting, paging, and other search query behaviors. From 1d3253c23dbc8a7bdf0011b5d67819568cdd1c08 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 13:41:01 -0700 Subject: [PATCH 13/40] update --- .../search/documents/_operations/_operations.py | 12 ++++++------ .../search/documents/aio/_operations/_operations.py | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index c6c4bdacb9fc..e22291794e9d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -200,7 +200,7 @@ def build_search_search_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_search_request( +def build_search_search_post_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -843,7 +843,7 @@ def _search_get( return deserialized # type: ignore @overload - def search( + def search_post( self, *, query_source_authorization: Optional[str] = None, @@ -1035,7 +1035,7 @@ def search( """ @overload - def search( + def search_post( self, body: JSON, *, @@ -1060,7 +1060,7 @@ def search( """ @overload - def search( + def search_post( self, body: IO[bytes], *, @@ -1085,7 +1085,7 @@ def search( """ @distributed_trace - def search( + def search_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -1332,7 +1332,7 @@ def search( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_search_request( + _request = build_search_search_post_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index 16b257d8734f..808bf9cb85f4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -35,7 +35,7 @@ build_search_get_document_request, build_search_index_documents_request, build_search_search_get_request, - build_search_search_request, + build_search_search_post_request, build_search_suggest_get_request, build_search_suggest_request, ) @@ -398,7 +398,7 @@ async def _search_get( return deserialized # type: ignore @overload - async def search( + async def search_post( self, *, query_source_authorization: Optional[str] = None, @@ -590,7 +590,7 @@ async def search( """ @overload - async def search( + async def search_post( self, body: JSON, *, @@ -615,7 +615,7 @@ async def search( """ @overload - async def search( + async def search_post( self, body: IO[bytes], *, @@ -640,7 +640,7 @@ async def search( """ @distributed_trace_async - async def search( + async def search_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -887,7 +887,7 @@ async def search( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_search_request( + _request = build_search_search_post_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, From a161e5b6be3e1cedd2374d8a4d3d99cf68928076 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 14:16:40 -0700 Subject: [PATCH 14/40] update --- .../search/documents/_operations/_patch.py | 633 +++++++++++++++++- .../azure/search/documents/_patch.py | 2 + .../documents/aio/_operations/_patch.py | 417 +++++++++++- 3 files changed, 1050 insertions(+), 2 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index f878bf789efc..28531a46cbd5 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -7,12 +7,316 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Dict, List, cast +from typing import Any, Dict, List, Optional, Union, cast +import base64 +import itertools +import json + +from azure.core.paging import ItemPaged, PageIterator +from azure.core.tracing.decorator import distributed_trace from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated from .. import models as _models +def _convert_search_result(result: _models.SearchResult) -> Dict[str, Any]: + """Convert SearchResult model to dictionary with @search.* metadata.""" + ret = dict(result.additional_properties) if result.additional_properties else {} + if result.score is not None: + ret["@search.score"] = result.score + if result.reranker_score is not None: + ret["@search.reranker_score"] = result.reranker_score + if result.highlights is not None: + ret["@search.highlights"] = result.highlights + if result.captions is not None: + ret["@search.captions"] = result.captions + if result.document_debug_info is not None: + ret["@search.document_debug_info"] = result.document_debug_info + if result.reranker_boosted_score is not None: + ret["@search.reranker_boosted_score"] = result.reranker_boosted_score + return ret + + +def _pack_continuation_token(response: _models.SearchDocumentsResult, api_version: str) -> Optional[bytes]: + """Pack continuation token from search response.""" + if response.next_page_parameters is not None: + token = { + "apiVersion": api_version, + "nextLink": response.next_link, + "nextPageParameters": response.next_page_parameters.as_dict(), + } + return base64.b64encode(json.dumps(token).encode("utf-8")) + return None + + +def _unpack_continuation_token(token: bytes) -> tuple: + """Unpack continuation token to get next link and request.""" + unpacked_token = json.loads(base64.b64decode(token)) + next_link = unpacked_token["nextLink"] + next_page_parameters = unpacked_token["nextPageParameters"] + next_page_request = _models.SearchRequest(**next_page_parameters) + return next_link, next_page_request + + +def _ensure_response(f): + """Decorator to ensure response is fetched before accessing metadata.""" + def wrapper(self, *args, **kw): + if self._current_page is None: + self._response = self._get_next(self.continuation_token) + self.continuation_token, self._current_page = self._extract_data(self._response) + return f(self, *args, **kw) + return wrapper + + +def _build_search_request( + search_text: Optional[str] = None, + *, + include_total_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[Union[List[str], str]] = None, + query_type: Optional[Union[str, _models.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + semantic_query: Optional[str] = None, + search_fields: Optional[Union[List[str], str]] = None, + search_mode: Optional[Union[str, _models.SearchMode]] = None, + query_language: Optional[Union[str, _models.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models.QuerySpellerType]] = None, + query_answer: Optional[Union[str, _models.QueryAnswerType]] = None, + query_answer_count: Optional[int] = None, + query_answer_threshold: Optional[float] = None, + query_caption: Optional[Union[str, _models.QueryCaptionType]] = None, + query_caption_highlight_enabled: Optional[bool] = None, + semantic_fields: Optional[Union[List[str], str]] = None, + semantic_configuration_name: Optional[str] = None, + select: Optional[Union[List[str], str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, + session_id: Optional[str] = None, + vector_queries: Optional[List[_models.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models.VectorFilterMode]] = None, + semantic_error_mode: Optional[Union[str, _models.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, + query_rewrites_count: Optional[int] = None, + debug: Optional[Union[str, _models.QueryDebugMode]] = None, + hybrid_search: Optional[_models.HybridSearch] = None, +) -> _models.SearchRequest: + """Build a SearchRequest from search parameters. + + This is a shared helper function used by both sync and async search methods. + """ + # Convert list parameters to comma-separated strings if needed + if isinstance(search_fields, list): + search_fields = ",".join(search_fields) + if isinstance(select, list): + select = ",".join(select) + if isinstance(order_by, list): + order_by = ",".join(order_by) + if isinstance(semantic_fields, list): + semantic_fields = ",".join(semantic_fields) + + # Build complex query parameters + answers = None + if query_answer: + answers = str(query_answer) + if query_answer_count is not None: + answers = f"{answers}|count-{query_answer_count}" + if query_answer_threshold is not None: + answers = f"{answers},threshold-{query_answer_threshold}" + + captions = None + if query_caption: + captions = str(query_caption) + if query_caption_highlight_enabled is not None: + captions = f"{captions}|highlight-{str(query_caption_highlight_enabled).lower()}" + + rewrites = None + if query_rewrites: + rewrites = str(query_rewrites) + if query_rewrites_count is not None: + rewrites = f"{rewrites}|count-{query_rewrites_count}" + + # Build and return the search request + return _models.SearchRequest( + search_text=search_text, + include_total_count=include_total_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + semantic_query=semantic_query, + search_fields=search_fields, + search_mode=search_mode, + query_language=query_language, + query_speller=query_speller, + answers=answers, + captions=captions, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, + skip=skip, + top=top, + session_id=session_id, + scoring_statistics=scoring_statistics, + vector_queries=vector_queries, + vector_filter_mode=vector_filter_mode, + semantic_error_handling=semantic_error_mode, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + query_rewrites=rewrites, + debug=debug, + hybrid_search=hybrid_search, + ) + + +class SearchPageIterator(PageIterator): + """An iterator over search result pages.""" + + def __init__(self, client, initial_request: _models.SearchRequest, kwargs, continuation_token=None) -> None: + super(SearchPageIterator, self).__init__( + get_next=self._get_next_cb, + extract_data=self._extract_data_cb, + continuation_token=continuation_token, + ) + self._client = client + self._initial_request = initial_request + self._kwargs = kwargs + self._facets: Optional[Dict[str, List[Dict[str, Any]]]] = None + self._api_version = kwargs.get("api_version", "2025-11-01-preview") + + def _get_next_cb(self, continuation_token): + if continuation_token is None: + return self._client.search_post(body=self._initial_request, **self._kwargs) + + _next_link, next_page_request = _unpack_continuation_token(continuation_token) + return self._client.search_post(body=next_page_request, **self._kwargs) + + def _extract_data_cb(self, response: _models.SearchDocumentsResult): + continuation_token = _pack_continuation_token(response, api_version=self._api_version) + results = [_convert_search_result(r) for r in response.results] + return continuation_token, results + + @_ensure_response + def get_facets(self) -> Optional[Dict[str, Any]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + if response.facets is not None and self._facets is None: + self._facets = {k: [x.as_dict() if hasattr(x, 'as_dict') else dict(x) for x in v] + for k, v in response.facets.items()} + return self._facets + + @_ensure_response + def get_coverage(self) -> Optional[float]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.coverage + + @_ensure_response + def get_count(self) -> Optional[int]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.count + + @_ensure_response + def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.answers + + @_ensure_response + def get_debug_info(self) -> Optional[_models.DebugInfo]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.debug_info + + +class SearchItemPaged(ItemPaged[Dict]): + """A pageable list of search results with metadata accessors.""" + + def __init__(self, page_iterator_factory_func) -> None: + # Store the factory function that creates SearchPageIterator instances + self._page_iterator_factory = page_iterator_factory_func + self._first_page_iterator_instance: Optional[SearchPageIterator] = None + # Initialize the parent without arguments - we'll override by_page() + self._page_iterator = None + + def by_page(self, continuation_token=None): + """Get an iterator of pages of results. + + :param continuation_token: Token to retrieve the next page of results + :type continuation_token: str or None + :return: An iterator of pages + :rtype: SearchPageIterator + """ + return self._page_iterator_factory(continuation_token) + + def __next__(self) -> Dict: + if self._page_iterator is None: + first_iterator = self._first_iterator_instance() + self._page_iterator = itertools.chain.from_iterable(first_iterator) + return next(self._page_iterator) + + def _first_iterator_instance(self) -> SearchPageIterator: + if self._first_page_iterator_instance is None: + self._first_page_iterator_instance = cast(SearchPageIterator, self.by_page()) + return self._first_page_iterator_instance + + def get_facets(self) -> Optional[Dict]: + """Return any facet results if faceting was requested. + + :return: facet results + :rtype: dict or None + """ + return self._first_iterator_instance().get_facets() + + def get_coverage(self) -> Optional[float]: + """Return the coverage percentage, if `minimum_coverage` was + specified for the query. + + :return: coverage percentage + :rtype: float or None + """ + return self._first_iterator_instance().get_coverage() + + def get_count(self) -> Optional[int]: + """Return the count of results if `include_total_count` was + set for the query. + + :return: count of results + :rtype: int or None + """ + return self._first_iterator_instance().get_count() + + def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + """Return semantic answers. Only included if the semantic ranker is used + and answers are requested in the search query via the query_answer parameter. + + :return: answers + :rtype: list[~azure.search.documents.models.QueryAnswerResult] or None + """ + return self._first_iterator_instance().get_answers() + + def get_debug_info(self) -> Optional[_models.DebugInfo]: + """Return the debug information for the query. + + :return: the debug information for the query + :rtype: ~azure.search.documents.models.DebugInfo or None + """ + return self._first_iterator_instance().get_debug_info() + + class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): """SearchClient operations mixin customizations.""" @@ -126,9 +430,336 @@ def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> Lis result = self.index_documents(batch, **kwargs) return cast(List[_models.IndexingResult], result.results) + @distributed_trace + def search( + self, + search_text: Optional[str] = None, + *, + include_total_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[Union[List[str], str]] = None, + query_type: Optional[Union[str, _models.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + semantic_query: Optional[str] = None, + search_fields: Optional[Union[List[str], str]] = None, + search_mode: Optional[Union[str, _models.SearchMode]] = None, + query_language: Optional[Union[str, _models.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models.QuerySpellerType]] = None, + query_answer: Optional[Union[str, _models.QueryAnswerType]] = None, + query_answer_count: Optional[int] = None, + query_answer_threshold: Optional[float] = None, + query_caption: Optional[Union[str, _models.QueryCaptionType]] = None, + query_caption_highlight_enabled: Optional[bool] = None, + semantic_fields: Optional[Union[List[str], str]] = None, + semantic_configuration_name: Optional[str] = None, + select: Optional[Union[List[str], str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, + session_id: Optional[str] = None, + vector_queries: Optional[List[_models.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models.VectorFilterMode]] = None, + semantic_error_mode: Optional[Union[str, _models.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, + query_rewrites_count: Optional[int] = None, + debug: Optional[Union[str, _models.QueryDebugMode]] = None, + hybrid_search: Optional[_models.HybridSearch] = None, + **kwargs: Any + ) -> SearchItemPaged[Dict]: + """Search the Azure search index for documents. + + :param str search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. + :keyword bool include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. + :keyword list[str] facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. + :keyword str filter: The OData $filter expression to apply to the search query. + :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is . + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is . + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :paramtype order_by: list[str] or str + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: + 'simple', 'full', "semantic". + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword list[str] scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). + :keyword str scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. + :keyword str semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. + :keyword search_fields: The list of field names to which to scope the full-text search. When + using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of + each fielded search expression take precedence over any field names listed in this parameter. + :paramtype search_fields: list[str] or str + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Possible values include: 'any', 'all'. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: The language of the search query. Possible values include: "none", "en-us", + "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", + "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", + "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", + "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", + "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", + "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", + "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk". + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Possible values include: "none", "lexicon". + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword query_answer: This parameter is only valid if the query type is 'semantic'. If set, + the query returns answers extracted from key passages in the highest ranked documents. + Possible values include: "none", "extractive". + :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType + :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and + query answer is 'extractive'. Configures the number of answers returned. Default count is 1. + :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and + query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. + :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the + query returns captions extracted from key passages in the highest ranked documents. + Defaults to 'None'. Possible values include: "none", "extractive". + :paramtype query_caption: str or ~azure.search.documents.models.QueryCaptionType + :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when + query caption is set to 'extractive'. Determines whether highlighting is enabled. + Defaults to 'true'. + :keyword semantic_fields: The list of field names used for semantic search. + :paramtype semantic_fields: list[str] or str + :keyword semantic_configuration_name: The name of the semantic configuration that will be used when + processing documents for queries of type semantic. + :paramtype semantic_configuration_name: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as retrievable + in the schema are included. + :paramtype select: list[str] or str + :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + :keyword int top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. + Possible values include: "local", "global". + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword str session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. + :keyword semantic_error_mode: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". + :paramtype semantic_error_mode: str or ~azure.search.documents.models.SemanticErrorMode + :keyword int semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of + time it takes for semantic enrichment to finish processing before the request fails. + :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword int query_rewrites_count: This parameter is only valid if the query rewrites type is 'generative'. + Configures the number of rewrites returned. Default count is 10. + :keyword debug: Enables a debugging tool that can be used to further explore your Semantic search + results. Known values are: "disabled", "speller", "semantic", and "all". + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword vector_queries: The query parameters for vector and hybrid search queries. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch + :return: List of search results. + :rtype: SearchItemPaged[dict] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_simple_query.py + :start-after: [START simple_query] + :end-before: [END simple_query] + :language: python + :dedent: 4 + :caption: Search on a simple text term. + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_filter_query.py + :start-after: [START filter_query] + :end-before: [END filter_query] + :language: python + :dedent: 4 + :caption: Filter and sort search results. + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_facet_query.py + :start-after: [START facet_query] + :end-before: [END facet_query] + :language: python + :dedent: 4 + :caption: Get search result facets. + """ + # Convert list parameters to comma-separated strings if needed + if isinstance(search_fields, list): + search_fields = ",".join(search_fields) + if isinstance(select, list): + select = ",".join(select) + if isinstance(order_by, list): + order_by = ",".join(order_by) + if isinstance(semantic_fields, list): + semantic_fields = ",".join(semantic_fields) + + # Build complex query parameters + answers = None + if query_answer: + answers = str(query_answer) + if query_answer_count is not None: + answers = f"{answers}|count-{query_answer_count}" + if query_answer_threshold is not None: + answers = f"{answers},threshold-{query_answer_threshold}" + + captions = None + if query_caption: + captions = str(query_caption) + if query_caption_highlight_enabled is not None: + captions = f"{captions}|highlight-{str(query_caption_highlight_enabled).lower()}" + + rewrites = None + if query_rewrites: + rewrites = str(query_rewrites) + if query_rewrites_count is not None: + rewrites = f"{rewrites}|count-{query_rewrites_count}" + + # Build the search request + search_request = _models.SearchRequest( + search_text=search_text, + include_total_count=include_total_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + semantic_query=semantic_query, + search_fields=search_fields, + search_mode=search_mode, + query_language=query_language, + query_speller=query_speller, + answers=answers, + captions=captions, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, + skip=skip, + top=top, + session_id=session_id, + scoring_statistics=scoring_statistics, + vector_queries=vector_queries, + vector_filter_mode=vector_filter_mode, + semantic_error_handling=semantic_error_mode, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + query_rewrites=rewrites, + debug=debug, + hybrid_search=hybrid_search, + ) + + # Build the search request using shared helper + search_request = _build_search_request( + search_text=search_text, + include_total_count=include_total_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + semantic_query=semantic_query, + search_fields=search_fields, + search_mode=search_mode, + query_language=query_language, + query_speller=query_speller, + query_answer=query_answer, + query_answer_count=query_answer_count, + query_answer_threshold=query_answer_threshold, + query_caption=query_caption, + query_caption_highlight_enabled=query_caption_highlight_enabled, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, + skip=skip, + top=top, + scoring_statistics=scoring_statistics, + session_id=session_id, + vector_queries=vector_queries, + vector_filter_mode=vector_filter_mode, + semantic_error_mode=semantic_error_mode, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + query_rewrites=query_rewrites, + query_rewrites_count=query_rewrites_count, + debug=debug, + hybrid_search=hybrid_search, + ) + + # Create kwargs for the search_post call + search_kwargs = dict(kwargs) + + # Create a factory function that returns a page iterator + # This is compatible with ItemPaged's by_page() pattern + def page_iterator_factory(continuation_token=None): + return SearchPageIterator( + client=self, + initial_request=search_request, + kwargs=search_kwargs, + continuation_token=continuation_token + ) + + # Return SearchItemPaged with the factory function + return SearchItemPaged(page_iterator_factory) + __all__: list[str] = [ "_SearchClientOperationsMixin", + "SearchItemPaged", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index d611df824199..5a9bf72abbae 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -10,6 +10,7 @@ from enum import Enum from azure.core import CaseInsensitiveEnumMeta from ._client import SearchClient as _SearchClient +from ._operations._patch import SearchItemPaged class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -31,6 +32,7 @@ def __init__(self, endpoint, index_name, credential, **kwargs): __all__: list[str] = [ "SearchClient", + "SearchItemPaged", "ApiVersion", "DEFAULT_VERSION", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 1a53b3bfbcba..7734bc02e473 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -7,12 +7,169 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Dict, List, cast +from typing import Any, Dict, List, Optional, Union, cast +import base64 +import json + +from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator +from azure.core.tracing.decorator_async import distributed_trace_async from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated +from ..._operations._patch import _build_search_request, _convert_search_result, _pack_continuation_token, _unpack_continuation_token from ... import models as _models +def _ensure_response(f): + """Decorator to ensure response is fetched before accessing metadata.""" + async def wrapper(self, *args, **kw): + if self._current_page is None: + self._response = await self._get_next(self.continuation_token) + self.continuation_token, self._current_page = await self._extract_data(self._response) + return await f(self, *args, **kw) + return wrapper + + +class AsyncSearchPageIterator(AsyncPageIterator): + """An async iterator over search result pages.""" + + def __init__(self, client, initial_request: _models.SearchRequest, kwargs, continuation_token=None) -> None: + super(AsyncSearchPageIterator, self).__init__( + get_next=self._get_next_cb, + extract_data=self._extract_data_cb, + continuation_token=continuation_token, + ) + self._client = client + self._initial_request = initial_request + self._kwargs = kwargs + self._facets: Optional[Dict[str, List[Dict[str, Any]]]] = None + self._api_version = kwargs.get("api_version", "2025-11-01-preview") + + async def _get_next_cb(self, continuation_token): + if continuation_token is None: + return await self._client.search_post(body=self._initial_request, **self._kwargs) + + _next_link, next_page_request = _unpack_continuation_token(continuation_token) + return await self._client.search_post(body=next_page_request, **self._kwargs) + + async def _extract_data_cb(self, response: _models.SearchDocumentsResult): + continuation_token = _pack_continuation_token(response, api_version=self._api_version) + results = [_convert_search_result(r) for r in response.results] + return continuation_token, results + + @_ensure_response + async def get_facets(self) -> Optional[Dict[str, Any]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + if response.facets is not None and self._facets is None: + self._facets = {k: [x.as_dict() if hasattr(x, 'as_dict') else dict(x) for x in v] + for k, v in response.facets.items()} + return self._facets + + @_ensure_response + async def get_coverage(self) -> Optional[float]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.coverage + + @_ensure_response + async def get_count(self) -> Optional[int]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.count + + @_ensure_response + async def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.answers + + @_ensure_response + async def get_debug_info(self) -> Optional[_models.DebugInfo]: + self.continuation_token = None + response = cast(_models.SearchDocumentsResult, self._response) + return response.debug_info + + +class AsyncSearchItemPaged(AsyncItemPaged[Dict]): + """An async pageable list of search results with metadata accessors.""" + + def __init__(self, page_iterator_factory_func) -> None: + # Store the factory function that creates AsyncSearchPageIterator instances + self._page_iterator_factory = page_iterator_factory_func + self._first_page_iterator_instance: Optional[AsyncSearchPageIterator] = None + self._page_iterator = None + self._page = None + + def by_page(self, continuation_token=None): + """Get an async iterator of pages of results. + + :param continuation_token: Token to retrieve the next page of results + :type continuation_token: str or None + :return: An async iterator of pages + :rtype: AsyncSearchPageIterator + """ + return self._page_iterator_factory(continuation_token) + + async def __anext__(self) -> Dict: + if self._page_iterator is None: + self._page_iterator = self.by_page() + if self._page is None: + self._page = await self._page_iterator.__anext__() + try: + return await self._page.__anext__() + except StopAsyncIteration: + self._page = None + return await self.__anext__() + + async def _first_iterator_instance(self) -> AsyncSearchPageIterator: + if self._first_page_iterator_instance is None: + self._first_page_iterator_instance = cast(AsyncSearchPageIterator, self.by_page()) + return self._first_page_iterator_instance + + async def get_facets(self) -> Optional[Dict]: + """Return any facet results if faceting was requested. + + :return: facet results + :rtype: dict or None + """ + return await (await self._first_iterator_instance()).get_facets() + + async def get_coverage(self) -> Optional[float]: + """Return the coverage percentage, if `minimum_coverage` was + specified for the query. + + :return: coverage percentage + :rtype: float or None + """ + return await (await self._first_iterator_instance()).get_coverage() + + async def get_count(self) -> Optional[int]: + """Return the count of results if `include_total_count` was + set for the query. + + :return: count of results + :rtype: int or None + """ + return await (await self._first_iterator_instance()).get_count() + + async def get_answers(self) -> Optional[List[_models.QueryAnswerResult]]: + """Return semantic answers. Only included if the semantic ranker is used + and answers are requested in the search query via the query_answer parameter. + + :return: answers + :rtype: list[~azure.search.documents.models.QueryAnswerResult] or None + """ + return await (await self._first_iterator_instance()).get_answers() + + async def get_debug_info(self) -> Optional[_models.DebugInfo]: + """Return the debug information for the query. + + :return: the debug information for the query + :rtype: ~azure.search.documents.models.DebugInfo or None + """ + return await (await self._first_iterator_instance()).get_debug_info() + + class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): """Async SearchClient operations mixin customizations.""" @@ -126,9 +283,267 @@ async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) result = await self.index_documents(batch, **kwargs) return cast(List[_models.IndexingResult], result.results) + @distributed_trace_async + async def search( + self, + search_text: Optional[str] = None, + *, + include_total_count: Optional[bool] = None, + facets: Optional[List[str]] = None, + filter: Optional[str] = None, + highlight_fields: Optional[str] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[Union[List[str], str]] = None, + query_type: Optional[Union[str, _models.QueryType]] = None, + scoring_parameters: Optional[List[str]] = None, + scoring_profile: Optional[str] = None, + semantic_query: Optional[str] = None, + search_fields: Optional[Union[List[str], str]] = None, + search_mode: Optional[Union[str, _models.SearchMode]] = None, + query_language: Optional[Union[str, _models.QueryLanguage]] = None, + query_speller: Optional[Union[str, _models.QuerySpellerType]] = None, + query_answer: Optional[Union[str, _models.QueryAnswerType]] = None, + query_answer_count: Optional[int] = None, + query_answer_threshold: Optional[float] = None, + query_caption: Optional[Union[str, _models.QueryCaptionType]] = None, + query_caption_highlight_enabled: Optional[bool] = None, + semantic_fields: Optional[Union[List[str], str]] = None, + semantic_configuration_name: Optional[str] = None, + select: Optional[Union[List[str], str]] = None, + skip: Optional[int] = None, + top: Optional[int] = None, + scoring_statistics: Optional[Union[str, _models.ScoringStatistics]] = None, + session_id: Optional[str] = None, + vector_queries: Optional[List[_models.VectorQuery]] = None, + vector_filter_mode: Optional[Union[str, _models.VectorFilterMode]] = None, + semantic_error_mode: Optional[Union[str, _models.SemanticErrorMode]] = None, + semantic_max_wait_in_milliseconds: Optional[int] = None, + query_rewrites: Optional[Union[str, _models.QueryRewritesType]] = None, + query_rewrites_count: Optional[int] = None, + debug: Optional[Union[str, _models.QueryDebugMode]] = None, + hybrid_search: Optional[_models.HybridSearch] = None, + **kwargs: Any + ) -> AsyncSearchItemPaged[Dict]: + """Search the Azure search index for documents. + + :param str search_text: A full-text search query expression; Use "*" or omit this parameter to + match all documents. + :keyword bool include_total_count: A value that specifies whether to fetch the total count of + results. Default is false. Setting this value to true may have a performance impact. Note that + the count returned is an approximation. + :keyword list[str] facets: The list of facet expressions to apply to the search query. Each facet + expression contains a field name, optionally followed by a comma-separated list of name:value + pairs. + :keyword str filter: The OData $filter expression to apply to the search query. + :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. + Only searchable fields can be used for hit highlighting. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. Default is . + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. Default is . + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. This + parameter can be useful for ensuring search availability even for services with only one + replica. The default is 100. + :keyword order_by: The list of OData $orderby expressions by which to sort the results. Each + expression can be either a field name or a call to either the geo.distance() or the + search.score() functions. Each expression can be followed by asc to indicate ascending, and + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no OrderBy is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :paramtype order_by: list[str] or str + :keyword query_type: A value that specifies the syntax of the search query. The default is + 'simple'. Use 'full' if your query uses the Lucene query syntax. Possible values include: + 'simple', 'full', "semantic". + :paramtype query_type: str or ~azure.search.documents.models.QueryType + :keyword list[str] scoring_parameters: The list of parameter values to be used in scoring functions (for + example, referencePointParameter) using the format name-values. For example, if the scoring + profile defines a function with a parameter called 'mylocation' the parameter string would be + "mylocation--122.2,44.8" (without the quotes). + :keyword str scoring_profile: The name of a scoring profile to evaluate match scores for matching + documents in order to sort the results. + :keyword str semantic_query: Allows setting a separate search query that will be solely used for + semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there + is a need to use different queries between the base retrieval and ranking phase, and the L2 + semantic phase. + :keyword search_fields: The list of field names to which to scope the full-text search. When + using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of + each fielded search expression take precedence over any field names listed in this parameter. + :paramtype search_fields: list[str] or str + :keyword search_mode: A value that specifies whether any or all of the search terms must be + matched in order to count the document as a match. Possible values include: 'any', 'all'. + :paramtype search_mode: str or ~azure.search.documents.models.SearchMode + :keyword query_language: The language of the search query. Possible values include: "none", "en-us", + "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", + "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", + "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", + "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", + "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", "et-ee", "ca-es", + "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", "gl-es", + "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk". + :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage + :keyword query_speller: A value that specified the type of the speller to use to spell-correct + individual search query terms. Possible values include: "none", "lexicon". + :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType + :keyword query_answer: This parameter is only valid if the query type is 'semantic'. If set, + the query returns answers extracted from key passages in the highest ranked documents. + Possible values include: "none", "extractive". + :paramtype query_answer: str or ~azure.search.documents.models.QueryAnswerType + :keyword int query_answer_count: This parameter is only valid if the query type is 'semantic' and + query answer is 'extractive'. Configures the number of answers returned. Default count is 1. + :keyword float query_answer_threshold: This parameter is only valid if the query type is 'semantic' and + query answer is 'extractive'. Configures the number of confidence threshold. Default count is 0.7. + :keyword query_caption: This parameter is only valid if the query type is 'semantic'. If set, the + query returns captions extracted from key passages in the highest ranked documents. + Defaults to 'None'. Possible values include: "none", "extractive". + :paramtype query_caption: str or ~azure.search.documents.models.QueryCaptionType + :keyword bool query_caption_highlight_enabled: This parameter is only valid if the query type is 'semantic' when + query caption is set to 'extractive'. Determines whether highlighting is enabled. + Defaults to 'true'. + :keyword semantic_fields: The list of field names used for semantic search. + :paramtype semantic_fields: list[str] or str + :keyword semantic_configuration_name: The name of the semantic configuration that will be used when + processing documents for queries of type semantic. + :paramtype semantic_configuration_name: str + :keyword select: The list of fields to retrieve. If unspecified, all fields marked as retrievable + in the schema are included. + :paramtype select: list[str] or str + :keyword int skip: The number of search results to skip. This value cannot be greater than 100,000. + If you need to scan documents in sequence, but cannot use $skip due to this limitation, + consider using $orderby on a totally-ordered key and $filter with a range query instead. + :keyword int top: The number of search results to retrieve. This can be used in conjunction with + $skip to implement client-side paging of search results. If results are truncated due to + server-side paging, the response will include a continuation token that can be used to issue + another Search request for the next page of results. + :keyword scoring_statistics: A value that specifies whether we want to calculate scoring + statistics (such as document frequency) globally for more consistent scoring, or locally, for + lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally + before scoring. Using global scoring statistics can increase latency of search queries. + Possible values include: "local", "global". + :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics + :keyword str session_id: A value to be used to create a sticky session, which can help getting more + consistent results. As long as the same sessionId is used, a best-effort attempt will be made + to target the same replica set. Be wary that reusing the same sessionID values repeatedly can + interfere with the load balancing of the requests across replicas and adversely affect the + performance of the search service. The value used as sessionId cannot start with a '_' + character. + :keyword semantic_error_mode: Allows the user to choose whether a semantic call should fail + completely (default / current behavior), or to return partial results. Known values are: + "partial" and "fail". + :paramtype semantic_error_mode: str or ~azure.search.documents.models.SemanticErrorMode + :keyword int semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount of + time it takes for semantic enrichment to finish processing before the request fails. + :keyword query_rewrites: When QueryRewrites is set to ``generative``\\ , the query terms are sent + to a generate model which will produce 10 (default) rewrites to help increase the recall of the + request. The requested count can be configured by appending the pipe character ``|`` followed + by the ``count-`` option, such as ``generative|count-3``. Defaults to + ``None``. This parameter is only valid if the query type is ``semantic``. Known values are: + "none" and "generative". + :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType + :keyword int query_rewrites_count: This parameter is only valid if the query rewrites type is 'generative'. + Configures the number of rewrites returned. Default count is 10. + :keyword debug: Enables a debugging tool that can be used to further explore your Semantic search + results. Known values are: "disabled", "speller", "semantic", and "all". + :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode + :keyword vector_queries: The query parameters for vector and hybrid search queries. + :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] + :keyword vector_filter_mode: Determines whether or not filters are applied before or after the + vector search is performed. Default is 'preFilter'. Known values are: "postFilter" and "preFilter". + :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode + :keyword hybrid_search: The query parameters to configure hybrid search behaviors. + :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch + :return: List of search results. + :rtype: AsyncSearchItemPaged[dict] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_simple_query_async.py + :start-after: [START simple_query_async] + :end-before: [END simple_query_async] + :language: python + :dedent: 4 + :caption: Search on a simple text term. + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_filter_query_async.py + :start-after: [START filter_query_async] + :end-before: [END filter_query_async] + :language: python + :dedent: 4 + :caption: Filter and sort search results. + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_facet_query_async.py + :start-after: [START facet_query_async] + :end-before: [END facet_query_async] + :language: python + :dedent: 4 + :caption: Get search result facets. + """ + # Build the search request using shared helper + search_request = _build_search_request( + search_text=search_text, + include_total_count=include_total_count, + facets=facets, + filter=filter, + highlight_fields=highlight_fields, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + query_type=query_type, + scoring_parameters=scoring_parameters, + scoring_profile=scoring_profile, + semantic_query=semantic_query, + search_fields=search_fields, + search_mode=search_mode, + query_language=query_language, + query_speller=query_speller, + query_answer=query_answer, + query_answer_count=query_answer_count, + query_answer_threshold=query_answer_threshold, + query_caption=query_caption, + query_caption_highlight_enabled=query_caption_highlight_enabled, + semantic_fields=semantic_fields, + semantic_configuration_name=semantic_configuration_name, + select=select, + skip=skip, + top=top, + scoring_statistics=scoring_statistics, + session_id=session_id, + vector_queries=vector_queries, + vector_filter_mode=vector_filter_mode, + semantic_error_mode=semantic_error_mode, + semantic_max_wait_in_milliseconds=semantic_max_wait_in_milliseconds, + query_rewrites=query_rewrites, + query_rewrites_count=query_rewrites_count, + debug=debug, + hybrid_search=hybrid_search, + ) + + # Create kwargs for the search_post call + search_kwargs = dict(kwargs) + + # Create a factory function that returns an async page iterator + def page_iterator_factory(continuation_token=None): + return AsyncSearchPageIterator( + client=self, + initial_request=search_request, + kwargs=search_kwargs, + continuation_token=continuation_token + ) + + # Return AsyncSearchItemPaged with the factory function + return AsyncSearchItemPaged(page_iterator_factory) + __all__: list[str] = [ "_SearchClientOperationsMixin", + "AsyncSearchItemPaged", ] # Add all objects you want publicly available to users at this package level From b507857fe5c5b27b2e37fe9f4c28952b96f9a2ba Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 14:28:44 -0700 Subject: [PATCH 15/40] update --- .../search/documents/_operations/_patch.py | 46 +++++++++---------- .../documents/aio/_operations/_patch.py | 31 +++++++------ 2 files changed, 41 insertions(+), 36 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 28531a46cbd5..962ff8e408b4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -60,11 +60,13 @@ def _unpack_continuation_token(token: bytes) -> tuple: def _ensure_response(f): """Decorator to ensure response is fetched before accessing metadata.""" + def wrapper(self, *args, **kw): if self._current_page is None: self._response = self._get_next(self.continuation_token) self.continuation_token, self._current_page = self._extract_data(self._response) return f(self, *args, **kw) + return wrapper @@ -109,7 +111,7 @@ def _build_search_request( hybrid_search: Optional[_models.HybridSearch] = None, ) -> _models.SearchRequest: """Build a SearchRequest from search parameters. - + This is a shared helper function used by both sync and async search methods. """ # Convert list parameters to comma-separated strings if needed @@ -121,7 +123,7 @@ def _build_search_request( order_by = ",".join(order_by) if isinstance(semantic_fields, list): semantic_fields = ",".join(semantic_fields) - + # Build complex query parameters answers = None if query_answer: @@ -130,19 +132,19 @@ def _build_search_request( answers = f"{answers}|count-{query_answer_count}" if query_answer_threshold is not None: answers = f"{answers},threshold-{query_answer_threshold}" - + captions = None if query_caption: captions = str(query_caption) if query_caption_highlight_enabled is not None: captions = f"{captions}|highlight-{str(query_caption_highlight_enabled).lower()}" - + rewrites = None if query_rewrites: rewrites = str(query_rewrites) if query_rewrites_count is not None: rewrites = f"{rewrites}|count-{query_rewrites_count}" - + # Build and return the search request return _models.SearchRequest( search_text=search_text, @@ -199,7 +201,7 @@ def __init__(self, client, initial_request: _models.SearchRequest, kwargs, conti def _get_next_cb(self, continuation_token): if continuation_token is None: return self._client.search_post(body=self._initial_request, **self._kwargs) - + _next_link, next_page_request = _unpack_continuation_token(continuation_token) return self._client.search_post(body=next_page_request, **self._kwargs) @@ -213,8 +215,9 @@ def get_facets(self) -> Optional[Dict[str, Any]]: self.continuation_token = None response = cast(_models.SearchDocumentsResult, self._response) if response.facets is not None and self._facets is None: - self._facets = {k: [x.as_dict() if hasattr(x, 'as_dict') else dict(x) for x in v] - for k, v in response.facets.items()} + self._facets = { + k: [x.as_dict() if hasattr(x, "as_dict") else dict(x) for x in v] for k, v in response.facets.items() + } return self._facets @_ensure_response @@ -251,10 +254,10 @@ def __init__(self, page_iterator_factory_func) -> None: self._first_page_iterator_instance: Optional[SearchPageIterator] = None # Initialize the parent without arguments - we'll override by_page() self._page_iterator = None - + def by_page(self, continuation_token=None): """Get an iterator of pages of results. - + :param continuation_token: Token to retrieve the next page of results :type continuation_token: str or None :return: An iterator of pages @@ -471,7 +474,7 @@ def search( query_rewrites_count: Optional[int] = None, debug: Optional[Union[str, _models.QueryDebugMode]] = None, hybrid_search: Optional[_models.HybridSearch] = None, - **kwargs: Any + **kwargs: Any, ) -> SearchItemPaged[Dict]: """Search the Azure search index for documents. @@ -640,7 +643,7 @@ def search( order_by = ",".join(order_by) if isinstance(semantic_fields, list): semantic_fields = ",".join(semantic_fields) - + # Build complex query parameters answers = None if query_answer: @@ -649,19 +652,19 @@ def search( answers = f"{answers}|count-{query_answer_count}" if query_answer_threshold is not None: answers = f"{answers},threshold-{query_answer_threshold}" - + captions = None if query_caption: captions = str(query_caption) if query_caption_highlight_enabled is not None: captions = f"{captions}|highlight-{str(query_caption_highlight_enabled).lower()}" - + rewrites = None if query_rewrites: rewrites = str(query_rewrites) if query_rewrites_count is not None: rewrites = f"{rewrites}|count-{query_rewrites_count}" - + # Build the search request search_request = _models.SearchRequest( search_text=search_text, @@ -698,7 +701,7 @@ def search( debug=debug, hybrid_search=hybrid_search, ) - + # Build the search request using shared helper search_request = _build_search_request( search_text=search_text, @@ -739,20 +742,17 @@ def search( debug=debug, hybrid_search=hybrid_search, ) - + # Create kwargs for the search_post call search_kwargs = dict(kwargs) - + # Create a factory function that returns a page iterator # This is compatible with ItemPaged's by_page() pattern def page_iterator_factory(continuation_token=None): return SearchPageIterator( - client=self, - initial_request=search_request, - kwargs=search_kwargs, - continuation_token=continuation_token + client=self, initial_request=search_request, kwargs=search_kwargs, continuation_token=continuation_token ) - + # Return SearchItemPaged with the factory function return SearchItemPaged(page_iterator_factory) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 7734bc02e473..6519f58d1f21 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -15,17 +15,24 @@ from azure.core.tracing.decorator_async import distributed_trace_async from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated -from ..._operations._patch import _build_search_request, _convert_search_result, _pack_continuation_token, _unpack_continuation_token +from ..._operations._patch import ( + _build_search_request, + _convert_search_result, + _pack_continuation_token, + _unpack_continuation_token, +) from ... import models as _models def _ensure_response(f): """Decorator to ensure response is fetched before accessing metadata.""" + async def wrapper(self, *args, **kw): if self._current_page is None: self._response = await self._get_next(self.continuation_token) self.continuation_token, self._current_page = await self._extract_data(self._response) return await f(self, *args, **kw) + return wrapper @@ -47,7 +54,7 @@ def __init__(self, client, initial_request: _models.SearchRequest, kwargs, conti async def _get_next_cb(self, continuation_token): if continuation_token is None: return await self._client.search_post(body=self._initial_request, **self._kwargs) - + _next_link, next_page_request = _unpack_continuation_token(continuation_token) return await self._client.search_post(body=next_page_request, **self._kwargs) @@ -61,8 +68,9 @@ async def get_facets(self) -> Optional[Dict[str, Any]]: self.continuation_token = None response = cast(_models.SearchDocumentsResult, self._response) if response.facets is not None and self._facets is None: - self._facets = {k: [x.as_dict() if hasattr(x, 'as_dict') else dict(x) for x in v] - for k, v in response.facets.items()} + self._facets = { + k: [x.as_dict() if hasattr(x, "as_dict") else dict(x) for x in v] for k, v in response.facets.items() + } return self._facets @_ensure_response @@ -99,10 +107,10 @@ def __init__(self, page_iterator_factory_func) -> None: self._first_page_iterator_instance: Optional[AsyncSearchPageIterator] = None self._page_iterator = None self._page = None - + def by_page(self, continuation_token=None): """Get an async iterator of pages of results. - + :param continuation_token: Token to retrieve the next page of results :type continuation_token: str or None :return: An async iterator of pages @@ -524,19 +532,16 @@ async def search( debug=debug, hybrid_search=hybrid_search, ) - + # Create kwargs for the search_post call search_kwargs = dict(kwargs) - + # Create a factory function that returns an async page iterator def page_iterator_factory(continuation_token=None): return AsyncSearchPageIterator( - client=self, - initial_request=search_request, - kwargs=search_kwargs, - continuation_token=continuation_token + client=self, initial_request=search_request, kwargs=search_kwargs, continuation_token=continuation_token ) - + # Return AsyncSearchItemPaged with the factory function return AsyncSearchItemPaged(page_iterator_factory) From 979c3a2920e4a2cc063a3749b12f2298dcb1f677 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 27 Oct 2025 16:46:55 -0700 Subject: [PATCH 16/40] update --- .../documents/_operations/_operations.py | 420 +++++++----- .../documents/aio/_operations/_operations.py | 442 +++++++------ .../indexes/_operations/_operations.py | 596 ++++++++++------- .../indexes/aio/_operations/_operations.py | 618 +++++++++++------- .../documents/indexes/models/__init__.py | 12 - .../documents/indexes/models/_models.py | 181 ----- .../azure/search/documents/models/__init__.py | 2 - .../azure/search/documents/models/_models.py | 31 - 8 files changed, 1269 insertions(+), 1033 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index e22291794e9d..270f5fdda089 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -10,6 +10,7 @@ from io import IOBase import json from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core import PipelineClient from azure.core.exceptions import ( @@ -22,6 +23,7 @@ StreamConsumedError, map_error, ) +from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace @@ -1468,7 +1470,7 @@ def _suggest_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models1.SuggestDocumentsResult: + ) -> ItemPaged["_models1.SuggestResult"]: """Suggests documents in the index that match the given partial query text. :keyword search_text: The search text to use to suggest documents. Must be at least 1 @@ -1519,10 +1521,15 @@ def _suggest_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :return: An iterator like instance of SuggestResult + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.SuggestResult] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SuggestResult]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1531,60 +1538,80 @@ def _suggest_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models1.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _request = build_search_suggest_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by, - search_fields=search_fields, - select=select, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.SuggestDocumentsResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SuggestResult], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def suggest( @@ -1877,7 +1904,7 @@ def index_documents( query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.IndexDocumentsResult: + ) -> ItemPaged["_models1.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. @@ -1889,8 +1916,8 @@ def index_documents( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1902,7 +1929,7 @@ def index_documents( query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.IndexDocumentsResult: + ) -> ItemPaged["_models1.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. @@ -1914,8 +1941,8 @@ def index_documents( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1927,7 +1954,7 @@ def index_documents( query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.IndexDocumentsResult: + ) -> ItemPaged["_models1.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. @@ -1939,8 +1966,8 @@ def index_documents( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1951,7 +1978,7 @@ def index_documents( *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models1.IndexDocumentsResult: + ) -> ItemPaged["_models1.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, @@ -1961,10 +1988,16 @@ def index_documents( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[list[_models1.IndexingResult]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1972,13 +2005,6 @@ def index_documents( 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.IndexDocumentsResult] = kwargs.pop("cls", None) - content_type = content_type or "application/json" _content = None if isinstance(batch, (IOBase, bytes)): @@ -1986,46 +2012,71 @@ def index_documents( else: _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_documents_request( - index_name=self._config.index_name, - query_source_authorization=query_source_authorization, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 207]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.IndexDocumentsResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_documents_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.IndexingResult], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 207]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) @distributed_trace def _autocomplete_get( @@ -2043,7 +2094,7 @@ def _autocomplete_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models1.AutocompleteResult: + ) -> ItemPaged["_models1.AutocompleteItem"]: """Autocompletes incomplete query terms based on input text and matching terms in the index. :keyword search_text: The incomplete term which should be auto-completed. Required. @@ -2086,10 +2137,15 @@ def _autocomplete_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult + :return: An iterator like instance of AutocompleteItem + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.AutocompleteItem] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.AutocompleteItem]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2098,59 +2154,79 @@ def _autocomplete_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models1.AutocompleteResult] = kwargs.pop("cls", None) - - _request = build_search_autocomplete_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.AutocompleteResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.AutocompleteItem], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def autocomplete( diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index 808bf9cb85f4..61602cf98630 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -10,8 +10,10 @@ from io import IOBase import json from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -24,6 +26,7 @@ ) from azure.core.pipeline import PipelineResponse from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -1006,8 +1009,8 @@ async def get_document( return deserialized # type: ignore - @distributed_trace_async - async def _suggest_get( + @distributed_trace + def _suggest_get( self, *, search_text: str, @@ -1023,7 +1026,7 @@ async def _suggest_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models2.SuggestDocumentsResult: + ) -> AsyncItemPaged["_models2.SuggestResult"]: """Suggests documents in the index that match the given partial query text. :keyword search_text: The search text to use to suggest documents. Must be at least 1 @@ -1074,10 +1077,15 @@ async def _suggest_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :return: An iterator like instance of SuggestResult + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.SuggestResult] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SuggestResult]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1086,60 +1094,80 @@ async def _suggest_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models2.SuggestDocumentsResult] = kwargs.pop("cls", None) - - _request = build_search_suggest_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by, - search_fields=search_fields, - select=select, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.SuggestDocumentsResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SuggestResult], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def suggest( @@ -1425,14 +1453,14 @@ async def suggest( return deserialized # type: ignore @overload - async def index_documents( + def index_documents( self, batch: _models2.IndexDocumentsBatch, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.IndexDocumentsResult: + ) -> AsyncItemPaged["_models2.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. @@ -1444,20 +1472,20 @@ async def index_documents( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def index_documents( + def index_documents( self, batch: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.IndexDocumentsResult: + ) -> AsyncItemPaged["_models2.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. @@ -1469,20 +1497,20 @@ async def index_documents( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def index_documents( + def index_documents( self, batch: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.IndexDocumentsResult: + ) -> AsyncItemPaged["_models2.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Required. @@ -1494,19 +1522,19 @@ async def index_documents( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ - @distributed_trace_async - async def index_documents( + @distributed_trace + def index_documents( self, batch: Union[_models2.IndexDocumentsBatch, JSON, IO[bytes]], *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models2.IndexDocumentsResult: + ) -> AsyncItemPaged["_models2.IndexingResult"]: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, @@ -1516,10 +1544,16 @@ async def index_documents( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.IndexDocumentsResult + :return: An iterator like instance of IndexingResult + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[list[_models2.IndexingResult]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1527,13 +1561,6 @@ async def index_documents( 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.IndexDocumentsResult] = kwargs.pop("cls", None) - content_type = content_type or "application/json" _content = None if isinstance(batch, (IOBase, bytes)): @@ -1541,49 +1568,74 @@ async def index_documents( else: _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_documents_request( - index_name=self._config.index_name, - query_source_authorization=query_source_authorization, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 207]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.IndexDocumentsResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def _autocomplete_get( + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_index_documents_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.IndexingResult], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 207]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def _autocomplete_get( self, *, search_text: str, @@ -1598,7 +1650,7 @@ async def _autocomplete_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> _models2.AutocompleteResult: + ) -> AsyncItemPaged["_models2.AutocompleteItem"]: """Autocompletes incomplete query terms based on input text and matching terms in the index. :keyword search_text: The incomplete term which should be auto-completed. Required. @@ -1641,10 +1693,16 @@ async def _autocomplete_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult + :return: An iterator like instance of AutocompleteItem + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.AutocompleteItem] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.AutocompleteItem]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1653,59 +1711,79 @@ async def _autocomplete_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models2.AutocompleteResult] = kwargs.pop("cls", None) - - _request = build_search_autocomplete_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.AutocompleteResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + def prepare_request(next_link=None): + if not next_link: + + _request = build_search_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.AutocompleteItem], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def autocomplete( diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index a1c098ebbf2a..4897838586fc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -1766,17 +1766,22 @@ def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models1.Syno return deserialized # type: ignore @distributed_trace - def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSynonymMapsResult: + def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SynonymMap"]: """Lists all synonym maps available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult + :return: An iterator like instance of SynonymMap + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SynonymMap] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SynonymMap]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1785,48 +1790,68 @@ def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> _m } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListSynonymMapsResult] = kwargs.pop("cls", None) + _request = build_search_index_get_synonym_maps_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_index_get_synonym_maps_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SynonymMap], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListSynonymMapsResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def create_synonym_map( @@ -3617,14 +3642,18 @@ def get_agent(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: return deserialized # type: ignore @distributed_trace - def list_agents(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: + def list_agents(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeAgent"]: """Lists all agents available for a search service. - :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult + :return: An iterator like instance of KnowledgeAgent + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.KnowledgeAgent]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -3633,47 +3662,67 @@ def list_agents(self, **kwargs: Any) -> _models1.ListKnowledgeAgentsResult: } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) + _request = build_search_index_list_agents_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_index_list_agents_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.KnowledgeAgent], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListKnowledgeAgentsResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def create_agent( @@ -4116,14 +4165,18 @@ def get_knowledge_source(self, source_name: str, **kwargs: Any) -> _models1.Know return deserialized # type: ignore @distributed_trace - def list_knowledge_sources(self, **kwargs: Any) -> _models1.ListKnowledgeSourcesResult: + def list_knowledge_sources(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeSource"]: """Lists all knowledge sources available for a search service. - :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult + :return: An iterator like instance of KnowledgeSource + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.KnowledgeSource]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4132,47 +4185,67 @@ def list_knowledge_sources(self, **kwargs: Any) -> _models1.ListKnowledgeSources } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) + _request = build_search_index_list_knowledge_sources_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_index_list_knowledge_sources_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.KnowledgeSource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListKnowledgeSourcesResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def create_knowledge_source( @@ -4797,17 +4870,23 @@ def get_data_source_connection( @distributed_trace def get_data_source_connections( self, *, select: Optional[str] = None, **kwargs: Any - ) -> _models1.ListDataSourcesResult: + ) -> ItemPaged["_models1.SearchIndexerDataSourceConnection"]: """Lists all datasources available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult + :return: An iterator like instance of SearchIndexerDataSourceConnection + :rtype: + ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchIndexerDataSourceConnection]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4816,48 +4895,68 @@ def get_data_source_connections( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListDataSourcesResult] = kwargs.pop("cls", None) + _request = build_search_indexer_get_data_source_connections_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_indexer_get_data_source_connections_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchIndexerDataSourceConnection], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListDataSourcesResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def create_data_source_connection( @@ -5676,17 +5775,22 @@ def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexe return deserialized # type: ignore @distributed_trace - def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListIndexersResult: + def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SearchIndexer"]: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult + :return: An iterator like instance of SearchIndexer + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndexer] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchIndexer]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -5695,48 +5799,68 @@ def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _model } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListIndexersResult] = kwargs.pop("cls", None) + _request = build_search_indexer_get_indexers_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_indexer_get_indexers_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchIndexer], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListIndexersResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def create_indexer( @@ -6285,17 +6409,25 @@ def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models1.SearchInde return deserialized # type: ignore @distributed_trace - def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1.ListSkillsetsResult: + def get_skillsets( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models1.SearchIndexerSkillset"]: """List all skillsets in a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult + :return: An iterator like instance of SearchIndexerSkillset + :rtype: + ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndexerSkillset] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models1.SearchIndexerSkillset]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -6304,48 +6436,68 @@ def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _mode } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models1.ListSkillsetsResult] = kwargs.pop("cls", None) + _request = build_search_indexer_get_skillsets_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_indexer_get_skillsets_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models1.SearchIndexerSkillset], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models1.ListSkillsetsResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload def create_skillset( diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 13ac36cc8a0f..030ea9d91294 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -416,18 +416,24 @@ async def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models return deserialized # type: ignore - @distributed_trace_async - async def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSynonymMapsResult: + @distributed_trace + def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SynonymMap"]: """Lists all synonym maps available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSynonymMapsResult + :return: An iterator like instance of SynonymMap + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SynonymMap] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SynonymMap]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -436,48 +442,68 @@ async def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models2.ListSynonymMapsResult] = kwargs.pop("cls", None) + _request = build_search_index_get_synonym_maps_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_index_get_synonym_maps_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SynonymMap], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListSynonymMapsResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_synonym_map( @@ -2273,15 +2299,20 @@ async def get_agent(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeA return deserialized # type: ignore - @distributed_trace_async - async def list_agents(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult: + @distributed_trace + def list_agents(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeAgent"]: """Lists all agents available for a search service. - :return: ListKnowledgeAgentsResult. The ListKnowledgeAgentsResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeAgentsResult + :return: An iterator like instance of KnowledgeAgent + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.KnowledgeAgent]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2290,47 +2321,67 @@ async def list_agents(self, **kwargs: Any) -> _models2.ListKnowledgeAgentsResult } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models2.ListKnowledgeAgentsResult] = kwargs.pop("cls", None) + _request = build_search_index_list_agents_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_index_list_agents_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.KnowledgeAgent], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListKnowledgeAgentsResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_agent( @@ -2772,15 +2823,20 @@ async def get_knowledge_source(self, source_name: str, **kwargs: Any) -> _models return deserialized # type: ignore - @distributed_trace_async - async def list_knowledge_sources(self, **kwargs: Any) -> _models2.ListKnowledgeSourcesResult: + @distributed_trace + def list_knowledge_sources(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeSource"]: """Lists all knowledge sources available for a search service. - :return: ListKnowledgeSourcesResult. The ListKnowledgeSourcesResult is compatible with - MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListKnowledgeSourcesResult + :return: An iterator like instance of KnowledgeSource + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeSource] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.KnowledgeSource]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2789,47 +2845,67 @@ async def list_knowledge_sources(self, **kwargs: Any) -> _models2.ListKnowledgeS } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models2.ListKnowledgeSourcesResult] = kwargs.pop("cls", None) - - _request = build_search_index_list_knowledge_sources_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + def prepare_request(next_link=None): + if not next_link: - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + _request = build_search_index_list_knowledge_sources_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - response = pipeline_response.http_response + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + return _request - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListKnowledgeSourcesResult, response.json()) + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.KnowledgeSource], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + async def get_next(next_link=None): + _request = prepare_request(next_link) - return deserialized # type: ignore + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_knowledge_source( @@ -3451,20 +3527,26 @@ async def get_data_source_connection( return deserialized # type: ignore - @distributed_trace_async - async def get_data_source_connections( + @distributed_trace + def get_data_source_connections( self, *, select: Optional[str] = None, **kwargs: Any - ) -> _models2.ListDataSourcesResult: + ) -> AsyncItemPaged["_models2.SearchIndexerDataSourceConnection"]: """Lists all datasources available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListDataSourcesResult + :return: An iterator like instance of SearchIndexerDataSourceConnection + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchIndexerDataSourceConnection]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -3473,48 +3555,68 @@ async def get_data_source_connections( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models2.ListDataSourcesResult] = kwargs.pop("cls", None) + _request = build_search_indexer_get_data_source_connections_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_indexer_get_data_source_connections_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchIndexerDataSourceConnection], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListDataSourcesResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_data_source_connection( @@ -4332,18 +4434,24 @@ async def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models2.Search return deserialized # type: ignore - @distributed_trace_async - async def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListIndexersResult: + @distributed_trace + def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SearchIndexer"]: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListIndexersResult + :return: An iterator like instance of SearchIndexer + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndexer] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchIndexer]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4352,48 +4460,68 @@ async def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models2.ListIndexersResult] = kwargs.pop("cls", None) + _request = build_search_indexer_get_indexers_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_indexer_get_indexers_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchIndexer], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListIndexersResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_indexer( @@ -4941,18 +5069,26 @@ async def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models2.Sear return deserialized # type: ignore - @distributed_trace_async - async def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _models2.ListSkillsetsResult: + @distributed_trace + def get_skillsets( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models2.SearchIndexerSkillset"]: """List all skillsets in a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.ListSkillsetsResult + :return: An iterator like instance of SearchIndexerSkillset + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndexerSkillset] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models2.SearchIndexerSkillset]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4961,48 +5097,68 @@ async def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models2.ListSkillsetsResult] = kwargs.pop("cls", None) + _request = build_search_indexer_get_skillsets_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_search_indexer_get_skillsets_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(list[_models2.SearchIndexerSkillset], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models2.ListSkillsetsResult, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_skillset( diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py index e8a411dd0c58..a4a3a9d430e6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py @@ -108,12 +108,6 @@ LexicalNormalizer, LexicalTokenizer, LimitTokenFilter, - ListDataSourcesResult, - ListIndexersResult, - ListKnowledgeAgentsResult, - ListKnowledgeSourcesResult, - ListSkillsetsResult, - ListSynonymMapsResult, LuceneStandardAnalyzer, LuceneStandardTokenizer, MagnitudeScoringFunction, @@ -388,12 +382,6 @@ "LexicalNormalizer", "LexicalTokenizer", "LimitTokenFilter", - "ListDataSourcesResult", - "ListIndexersResult", - "ListKnowledgeAgentsResult", - "ListKnowledgeSourcesResult", - "ListSkillsetsResult", - "ListSynonymMapsResult", "LuceneStandardAnalyzer", "LuceneStandardTokenizer", "MagnitudeScoringFunction", diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 25820f5df628..3317664cc66e 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -5798,187 +5798,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.odata_type = "#Microsoft.Azure.Search.LimitTokenFilter" # type: ignore -class ListDataSourcesResult(_Model): - """Response from a List Datasources request. If successful, it includes the full definitions of - all datasources. - - :ivar data_sources: The datasources in the Search service. Required. - :vartype data_sources: - list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - """ - - data_sources: list["_models.SearchIndexerDataSourceConnection"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) - """The datasources in the Search service. Required.""" - - @overload - def __init__( - self, - *, - data_sources: list["_models.SearchIndexerDataSourceConnection"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ListIndexersResult(_Model): - """Response from a List Indexers request. If successful, it includes the full definitions of all - indexers. - - :ivar indexers: The indexers in the Search service. Required. - :vartype indexers: list[~azure.search.documents.indexes.models.SearchIndexer] - """ - - indexers: list["_models.SearchIndexer"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) - """The indexers in the Search service. Required.""" - - @overload - def __init__( - self, - *, - indexers: list["_models.SearchIndexer"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ListKnowledgeAgentsResult(_Model): - """Result from listing knowledge agents. - - :ivar value: The knowledge agents in the service. Required. - :vartype value: list[~azure.search.documents.indexes.models.KnowledgeAgent] - """ - - value: list["_models.KnowledgeAgent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The knowledge agents in the service. Required.""" - - @overload - def __init__( - self, - *, - value: list["_models.KnowledgeAgent"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ListKnowledgeSourcesResult(_Model): - """Result from listing knowledge sources. - - :ivar value: The knowledge sources in the service. Required. - :vartype value: list[~azure.search.documents.indexes.models.KnowledgeSource] - """ - - value: list["_models.KnowledgeSource"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The knowledge sources in the service. Required.""" - - @overload - def __init__( - self, - *, - value: list["_models.KnowledgeSource"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ListSkillsetsResult(_Model): - """Response from a list skillset request. If successful, it includes the full definitions of all - skillsets. - - :ivar skillsets: The skillsets defined in the Search service. Required. - :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - """ - - skillsets: list["_models.SearchIndexerSkillset"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) - """The skillsets defined in the Search service. Required.""" - - @overload - def __init__( - self, - *, - skillsets: list["_models.SearchIndexerSkillset"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ListSynonymMapsResult(_Model): - """Response from a List SynonymMaps request. If successful, it includes the full definitions of - all synonym maps. - - :ivar synonym_maps: The synonym maps in the Search service. Required. - :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] - """ - - synonym_maps: list["_models.SynonymMap"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) - """The synonym maps in the Search service. Required.""" - - @overload - def __init__( - self, - *, - synonym_maps: list["_models.SynonymMap"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class LuceneStandardAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StandardAnalyzer"): """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop filter. diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 131c2175237c..862c868a2f78 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -25,7 +25,6 @@ HybridSearch, IndexAction, IndexDocumentsBatch, - IndexDocumentsResult, IndexingResult, LookupDocument, QueryAnswerResult, @@ -93,7 +92,6 @@ "HybridSearch", "IndexAction", "IndexDocumentsBatch", - "IndexDocumentsResult", "IndexingResult", "LookupDocument", "QueryAnswerResult", diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index d76287449034..be53ba951cea 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -392,37 +392,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class IndexDocumentsResult(_Model): - """Response containing the status of operations for all documents in the indexing request. - - :ivar results: The list of status information for each document in the indexing request. - Required. - :vartype results: list[~azure.search.documents.models.IndexingResult] - """ - - results: list["_models.IndexingResult"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) - """The list of status information for each document in the indexing request. Required.""" - - @overload - def __init__( - self, - *, - results: list["_models.IndexingResult"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class IndexingResult(_Model): """Status of an indexing operation for a single document. From 7383bfbf524bb28eb02eaace12fcb114fba0d395 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 09:18:11 -0700 Subject: [PATCH 17/40] update --- .../documents/_operations/_operations.py | 876 ++++------------- .../documents/aio/_operations/_operations.py | 888 +++++------------- .../indexes/_operations/_operations.py | 404 +++----- .../indexes/aio/_operations/_operations.py | 416 ++++---- .../documents/indexes/models/_models.py | 125 +++ .../azure/search/documents/models/__init__.py | 6 - .../azure/search/documents/models/_models.py | 37 +- 7 files changed, 891 insertions(+), 1861 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index 270f5fdda089..fd081ab470ab 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -10,7 +10,6 @@ from io import IOBase import json from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse from azure.core import PipelineClient from azure.core.exceptions import ( @@ -23,7 +22,6 @@ StreamConsumedError, map_error, ) -from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace @@ -337,7 +335,7 @@ def build_search_suggest_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_suggest_request( +def build_search_suggest_post_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -370,7 +368,7 @@ def build_search_suggest_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_documents_request( +def build_search_index_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -464,7 +462,7 @@ def build_search_autocomplete_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_autocomplete_request( +def build_search_autocomplete_post_request( index_name: str, *, query_source_authorization: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -845,7 +843,7 @@ def _search_get( return deserialized # type: ignore @overload - def search_post( + def _search_post( self, *, query_source_authorization: Optional[str] = None, @@ -884,210 +882,28 @@ def search_post( vector_filter_mode: Optional[Union[str, _models1.VectorFilterMode]] = None, hybrid_search: Optional[_models1.HybridSearch] = None, **kwargs: Any - ) -> _models1.SearchDocumentsResult: - """Searches for documents in the index. - - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword include_total_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. Default value is None. - :paramtype include_total_count: bool - :keyword facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. Default value is None. - :paramtype facets: list[str] - :keyword filter: The OData $filter expression to apply to the search query. Default value is - None. - :paramtype filter: str - :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. Default value is None. - :paramtype highlight_fields: str - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. Default value is None. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. Default value is None. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. Default value is None. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. Default value is None. - :paramtype order_by: str - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". Default value is None. - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. Known - values are: "local" and "global". Default value is None. - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. Default value is None. - :paramtype session_id: str - :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). Default value is None. - :paramtype scoring_parameters: list[str] - :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. Default value is None. - :paramtype scoring_profile: str - :keyword debug: Enables a debugging tool that can be used to further explore your reranked - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". Default value is None. - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. Default value is None. - :paramtype search_text: str - :keyword search_fields: The comma-separated list of field names to which to scope the full-text - search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the - field names of each fielded search expression take precedence over any field names listed in - this parameter. Default value is None. - :paramtype search_fields: str - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". Default - value is None. - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: A value that specifies the language of the search query. Known values - are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", - "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", - "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", - "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", - "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", - "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", - "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", - "te-in", and "ur-pk". Default value is None. - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Known values are: "none" and "lexicon". Default value is None. - :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields - marked as retrievable in the schema are included. Default value is None. - :paramtype select: str - :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use skip due to this limitation, consider - using orderby on a totally-ordered key and filter with a range query instead. Default value is - None. - :paramtype skip: int - :keyword top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. Default value is None. - :paramtype top: int - :keyword semantic_configuration_name: The name of a semantic configuration that will be used - when processing documents for queries of type semantic. Default value is None. - :paramtype semantic_configuration_name: str - :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". Default value is None. - :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount - of time it takes for semantic enrichment to finish processing before the request fails. Default - value is None. - :paramtype semantic_max_wait_in_milliseconds: int - :keyword semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. Default value is None. - :paramtype semantic_query: str - :keyword answers: A value that specifies whether answers should be returned as part of the - search response. Known values are: "none" and "extractive". Default value is None. - :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType - :keyword captions: A value that specifies whether captions should be returned as part of the - search response. Known values are: "none" and "extractive". Default value is None. - :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType - :keyword query_rewrites: A value that specifies whether query rewrites should be generated to - augment the search query. Known values are: "none" and "generative". Default value is None. - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. - Default value is None. - :paramtype semantic_fields: str - :keyword vector_queries: The query parameters for vector and hybrid search queries. Default - value is None. - :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter' for new indexes. Known values are: - "postFilter", "preFilter", and "strictPostFilter". Default value is None. - :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default - value is None. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchDocumentsResult: ... @overload - def search_post( + def _search_post( self, body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchDocumentsResult: - """Searches for documents in the index. - - :param body: Required. - :type body: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchDocumentsResult: ... @overload - def search_post( + def _search_post( self, body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SearchDocumentsResult: - """Searches for documents in the index. - - :param body: Required. - :type body: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SearchDocumentsResult: ... @distributed_trace - def search_post( + def _search_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -1470,7 +1286,7 @@ def _suggest_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models1.SuggestResult"]: + ) -> _models1._models.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. :keyword search_text: The search text to use to suggest documents. Must be at least 1 @@ -1521,15 +1337,10 @@ def _suggest_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: An iterator like instance of SuggestResult - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.SuggestResult] + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.SuggestResult]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1538,83 +1349,65 @@ def _suggest_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_suggest_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by, - search_fields=search_fields, - select=select, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.SuggestResult], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models1._models.SuggestDocumentsResult] = kwargs.pop("cls", None) + + _request = build_search_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - return pipeline_response + response = pipeline_response.http_response - return ItemPaged(get_next, extract_data) + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - def suggest( + def _suggest_post( self, *, search_text: str, @@ -1631,117 +1424,28 @@ def suggest( select: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models1.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - :keyword search_text: The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. Required. - :paramtype search_text: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword filter: An OData expression that filters the documents considered for suggestions. - Default value is None. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - suggestion query. Default is false. When set to true, the query will find suggestions even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are - slower and consume more resources. Default value is None. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is - None. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is - None. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a suggestion query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. Default value is None. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. Default value is None. - :paramtype order_by: str - :keyword search_fields: The comma-separated list of field names to search for the specified - search text. Target fields must be included in the specified suggester. Default value is None. - :paramtype search_fields: str - :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. Default value is None. - :paramtype select: str - :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. - The default is 5. Default value is None. - :paramtype top: int - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1._models.SuggestDocumentsResult: ... @overload - def suggest( + def _suggest_post( self, body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - :param body: Required. - :type body: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1._models.SuggestDocumentsResult: ... @overload - def suggest( + def _suggest_post( self, body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - :param body: Required. - :type body: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1._models.SuggestDocumentsResult: ... @distributed_trace - def suggest( + def _suggest_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -1758,7 +1462,7 @@ def suggest( select: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models1.SuggestDocumentsResult: + ) -> _models1._models.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. :param body: Is either a JSON type or a IO[bytes] type. Required. @@ -1812,7 +1516,7 @@ def suggest( The default is 5. Default value is None. :paramtype top: int :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1827,7 +1531,7 @@ def suggest( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.SuggestDocumentsResult] = kwargs.pop("cls", None) + cls: ClsType[_models1._models.SuggestDocumentsResult] = kwargs.pop("cls", None) if body is _Unset: if search_text is _Unset: @@ -1855,7 +1559,7 @@ def suggest( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_suggest_request( + _request = build_search_suggest_post_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1889,7 +1593,9 @@ def suggest( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.SuggestDocumentsResult, response.json()) + deserialized = _deserialize( + _models1._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1897,88 +1603,41 @@ def suggest( return deserialized # type: ignore @overload - def index_documents( + def _index( self, batch: _models1.IndexDocumentsBatch, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> ItemPaged["_models1.IndexingResult"]: - """Sends a batch of document write actions to the index. - - :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexDocumentsBatch - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1._models.IndexDocumentsResult: ... @overload - def index_documents( + def _index( self, batch: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> ItemPaged["_models1.IndexingResult"]: - """Sends a batch of document write actions to the index. - - :param batch: The batch of index actions. Required. - :type batch: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1._models.IndexDocumentsResult: ... @overload - def index_documents( + def _index( self, batch: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> ItemPaged["_models1.IndexingResult"]: - """Sends a batch of document write actions to the index. - - :param batch: The batch of index actions. Required. - :type batch: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1._models.IndexDocumentsResult: ... @distributed_trace - def index_documents( + def _index( self, batch: Union[_models1.IndexDocumentsBatch, JSON, IO[bytes]], *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models1.IndexingResult"]: + ) -> _models1._models.IndexDocumentsResult: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, @@ -1988,16 +1647,10 @@ def index_documents( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.IndexingResult] + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.IndexDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[list[_models1.IndexingResult]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2005,6 +1658,13 @@ def index_documents( 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1._models.IndexDocumentsResult] = kwargs.pop("cls", None) + content_type = content_type or "application/json" _content = None if isinstance(batch, (IOBase, bytes)): @@ -2012,71 +1672,48 @@ def index_documents( else: _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_index_documents_request( - index_name=self._config.index_name, - query_source_authorization=query_source_authorization, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.IndexingResult], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _request = build_search_index_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - if response.status_code not in [200, 207]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + response = pipeline_response.http_response - return pipeline_response + if response.status_code not in [200, 207]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - return ItemPaged(get_next, extract_data) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.IndexDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @distributed_trace def _autocomplete_get( @@ -2094,7 +1731,7 @@ def _autocomplete_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models1.AutocompleteItem"]: + ) -> _models1._models.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. :keyword search_text: The incomplete term which should be auto-completed. Required. @@ -2137,15 +1774,10 @@ def _autocomplete_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: An iterator like instance of AutocompleteItem - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.models.AutocompleteItem] + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.AutocompleteItem]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2154,82 +1786,64 @@ def _autocomplete_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_autocomplete_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.AutocompleteItem], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + cls: ClsType[_models1._models.AutocompleteResult] = kwargs.pop("cls", None) - return pipeline_response + _request = build_search_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return ItemPaged(get_next, extract_data) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models1.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - def autocomplete( + def _autocomplete_post( self, *, search_text: str, @@ -2245,110 +1859,28 @@ def autocomplete( search_fields: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models1.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - :keyword search_text: The search text on which to base autocomplete results. Required. - :paramtype search_text: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - Default value is None. - :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. Default value is None. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will autocomplete terms even - if there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. Default value is None. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by an autocomplete query in order for the query to be reported as a - success. This parameter can be useful for ensuring search availability even for services with - only one replica. The default is 80. Default value is None. - :paramtype minimum_coverage: float - :keyword search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. Default value - is None. - :paramtype search_fields: str - :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 - and 100. The default is 5. Default value is None. - :paramtype top: int - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1._models.AutocompleteResult: ... @overload - def autocomplete( + def _autocomplete_post( self, body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - :param body: Required. - :type body: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1._models.AutocompleteResult: ... @overload - def autocomplete( + def _autocomplete_post( self, body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models1.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - :param body: Required. - :type body: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1._models.AutocompleteResult: ... @distributed_trace - def autocomplete( + def _autocomplete_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -2364,7 +1896,7 @@ def autocomplete( search_fields: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models1.AutocompleteResult: + ) -> _models1._models.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. :param body: Is either a JSON type or a IO[bytes] type. Required. @@ -2411,7 +1943,7 @@ def autocomplete( and 100. The default is 5. Default value is None. :paramtype top: int :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult + :rtype: ~azure.search.documents.models._models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2426,7 +1958,7 @@ def autocomplete( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.AutocompleteResult] = kwargs.pop("cls", None) + cls: ClsType[_models1._models.AutocompleteResult] = kwargs.pop("cls", None) if body is _Unset: if search_text is _Unset: @@ -2453,7 +1985,7 @@ def autocomplete( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_autocomplete_request( + _request = build_search_autocomplete_post_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -2487,7 +2019,9 @@ def autocomplete( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.AutocompleteResult, response.json()) + deserialized = _deserialize( + _models1._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index 61602cf98630..2238afb1bea7 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -10,10 +10,8 @@ from io import IOBase import json from typing import Any, Callable, IO, Optional, TypeVar, Union, overload -import urllib.parse from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -26,21 +24,20 @@ ) from azure.core.pipeline import PipelineResponse from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from ... import models as _models2 from ..._operations._operations import ( build_search_autocomplete_get_request, - build_search_autocomplete_request, + build_search_autocomplete_post_request, build_search_get_document_count_request, build_search_get_document_request, - build_search_index_documents_request, + build_search_index_request, build_search_search_get_request, build_search_search_post_request, build_search_suggest_get_request, - build_search_suggest_request, + build_search_suggest_post_request, ) from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.utils import ClientMixinABC @@ -401,7 +398,7 @@ async def _search_get( return deserialized # type: ignore @overload - async def search_post( + async def _search_post( self, *, query_source_authorization: Optional[str] = None, @@ -440,210 +437,28 @@ async def search_post( vector_filter_mode: Optional[Union[str, _models2.VectorFilterMode]] = None, hybrid_search: Optional[_models2.HybridSearch] = None, **kwargs: Any - ) -> _models2.SearchDocumentsResult: - """Searches for documents in the index. - - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword include_total_count: A value that specifies whether to fetch the total count of - results. Default is false. Setting this value to true may have a performance impact. Note that - the count returned is an approximation. Default value is None. - :paramtype include_total_count: bool - :keyword facets: The list of facet expressions to apply to the search query. Each facet - expression contains a field name, optionally followed by a comma-separated list of name:value - pairs. Default value is None. - :paramtype facets: list[str] - :keyword filter: The OData $filter expression to apply to the search query. Default value is - None. - :paramtype filter: str - :keyword highlight_fields: The comma-separated list of field names to use for hit highlights. - Only searchable fields can be used for hit highlighting. Default value is None. - :paramtype highlight_fields: str - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. Default is </em>. Default value is None. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. Default is <em>. Default value is None. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a search query in order for the query to be reported as a success. This - parameter can be useful for ensuring search availability even for services with only one - replica. The default is 100. Default value is None. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. Default value is None. - :paramtype order_by: str - :keyword query_type: A value that specifies the syntax of the search query. The default is - 'simple'. Use 'full' if your query uses the Lucene query syntax. Known values are: "simple", - "full", and "semantic". Default value is None. - :paramtype query_type: str or ~azure.search.documents.models.QueryType - :keyword scoring_statistics: A value that specifies whether we want to calculate scoring - statistics (such as document frequency) globally for more consistent scoring, or locally, for - lower latency. The default is 'local'. Use 'global' to aggregate scoring statistics globally - before scoring. Using global scoring statistics can increase latency of search queries. Known - values are: "local" and "global". Default value is None. - :paramtype scoring_statistics: str or ~azure.search.documents.models.ScoringStatistics - :keyword session_id: A value to be used to create a sticky session, which can help getting more - consistent results. As long as the same sessionId is used, a best-effort attempt will be made - to target the same replica set. Be wary that reusing the same sessionID values repeatedly can - interfere with the load balancing of the requests across replicas and adversely affect the - performance of the search service. The value used as sessionId cannot start with a '_' - character. Default value is None. - :paramtype session_id: str - :keyword scoring_parameters: The list of parameter values to be used in scoring functions (for - example, referencePointParameter) using the format name-values. For example, if the scoring - profile defines a function with a parameter called 'mylocation' the parameter string would be - "mylocation--122.2,44.8" (without the quotes). Default value is None. - :paramtype scoring_parameters: list[str] - :keyword scoring_profile: The name of a scoring profile to evaluate match scores for matching - documents in order to sort the results. Default value is None. - :paramtype scoring_profile: str - :keyword debug: Enables a debugging tool that can be used to further explore your reranked - results. Known values are: "disabled", "semantic", "vector", "queryRewrites", "innerHits", and - "all". Default value is None. - :paramtype debug: str or ~azure.search.documents.models.QueryDebugMode - :keyword search_text: A full-text search query expression; Use "*" or omit this parameter to - match all documents. Default value is None. - :paramtype search_text: str - :keyword search_fields: The comma-separated list of field names to which to scope the full-text - search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the - field names of each fielded search expression take precedence over any field names listed in - this parameter. Default value is None. - :paramtype search_fields: str - :keyword search_mode: A value that specifies whether any or all of the search terms must be - matched in order to count the document as a match. Known values are: "any" and "all". Default - value is None. - :paramtype search_mode: str or ~azure.search.documents.models.SearchMode - :keyword query_language: A value that specifies the language of the search query. Known values - are: "none", "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", - "es-mx", "zh-cn", "zh-tw", "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", - "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", - "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", "ms-my", "ms-bn", "sl-sl", - "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", "lv-lv", - "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", - "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", - "te-in", and "ur-pk". Default value is None. - :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct - individual search query terms. Known values are: "none" and "lexicon". Default value is None. - :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType - :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields - marked as retrievable in the schema are included. Default value is None. - :paramtype select: str - :keyword skip: The number of search results to skip. This value cannot be greater than 100,000. - If you need to scan documents in sequence, but cannot use skip due to this limitation, consider - using orderby on a totally-ordered key and filter with a range query instead. Default value is - None. - :paramtype skip: int - :keyword top: The number of search results to retrieve. This can be used in conjunction with - $skip to implement client-side paging of search results. If results are truncated due to - server-side paging, the response will include a continuation token that can be used to issue - another Search request for the next page of results. Default value is None. - :paramtype top: int - :keyword semantic_configuration_name: The name of a semantic configuration that will be used - when processing documents for queries of type semantic. Default value is None. - :paramtype semantic_configuration_name: str - :keyword semantic_error_handling: Allows the user to choose whether a semantic call should fail - completely (default / current behavior), or to return partial results. Known values are: - "partial" and "fail". Default value is None. - :paramtype semantic_error_handling: str or ~azure.search.documents.models.SemanticErrorMode - :keyword semantic_max_wait_in_milliseconds: Allows the user to set an upper bound on the amount - of time it takes for semantic enrichment to finish processing before the request fails. Default - value is None. - :paramtype semantic_max_wait_in_milliseconds: int - :keyword semantic_query: Allows setting a separate search query that will be solely used for - semantic reranking, semantic captions and semantic answers. Is useful for scenarios where there - is a need to use different queries between the base retrieval and ranking phase, and the L2 - semantic phase. Default value is None. - :paramtype semantic_query: str - :keyword answers: A value that specifies whether answers should be returned as part of the - search response. Known values are: "none" and "extractive". Default value is None. - :paramtype answers: str or ~azure.search.documents.models.QueryAnswerType - :keyword captions: A value that specifies whether captions should be returned as part of the - search response. Known values are: "none" and "extractive". Default value is None. - :paramtype captions: str or ~azure.search.documents.models.QueryCaptionType - :keyword query_rewrites: A value that specifies whether query rewrites should be generated to - augment the search query. Known values are: "none" and "generative". Default value is None. - :paramtype query_rewrites: str or ~azure.search.documents.models.QueryRewritesType - :keyword semantic_fields: The comma-separated list of field names used for semantic ranking. - Default value is None. - :paramtype semantic_fields: str - :keyword vector_queries: The query parameters for vector and hybrid search queries. Default - value is None. - :paramtype vector_queries: list[~azure.search.documents.models.VectorQuery] - :keyword vector_filter_mode: Determines whether or not filters are applied before or after the - vector search is performed. Default is 'preFilter' for new indexes. Known values are: - "postFilter", "preFilter", and "strictPostFilter". Default value is None. - :paramtype vector_filter_mode: str or ~azure.search.documents.models.VectorFilterMode - :keyword hybrid_search: The query parameters to configure hybrid search behaviors. Default - value is None. - :paramtype hybrid_search: ~azure.search.documents.models.HybridSearch - :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchDocumentsResult: ... @overload - async def search_post( + async def _search_post( self, body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchDocumentsResult: - """Searches for documents in the index. - - :param body: Required. - :type body: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchDocumentsResult: ... @overload - async def search_post( + async def _search_post( self, body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SearchDocumentsResult: - """Searches for documents in the index. - - :param body: Required. - :type body: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SearchDocumentsResult. The SearchDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SearchDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SearchDocumentsResult: ... @distributed_trace_async - async def search_post( + async def _search_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -1009,8 +824,8 @@ async def get_document( return deserialized # type: ignore - @distributed_trace - def _suggest_get( + @distributed_trace_async + async def _suggest_get( self, *, search_text: str, @@ -1026,7 +841,7 @@ def _suggest_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models2.SuggestResult"]: + ) -> _models2._models.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. :keyword search_text: The search text to use to suggest documents. Must be at least 1 @@ -1077,15 +892,10 @@ def _suggest_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: An iterator like instance of SuggestResult - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.SuggestResult] + :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.SuggestResult]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1094,83 +904,65 @@ def _suggest_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_suggest_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - order_by=order_by, - search_fields=search_fields, - select=select, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.SuggestResult], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + cls: ClsType[_models2._models.SuggestDocumentsResult] = kwargs.pop("cls", None) - return pipeline_response + _request = build_search_suggest_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return AsyncItemPaged(get_next, extract_data) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - async def suggest( + async def _suggest_post( self, *, search_text: str, @@ -1187,117 +979,28 @@ async def suggest( select: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models2.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - :keyword search_text: The search text to use to suggest documents. Must be at least 1 - character, and no more than 100 characters. Required. - :paramtype search_text: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword filter: An OData expression that filters the documents considered for suggestions. - Default value is None. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - suggestion query. Default is false. When set to true, the query will find suggestions even if - there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are - slower and consume more resources. Default value is None. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting of suggestions is disabled. Default value is - None. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting of suggestions is disabled. Default value is - None. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by a suggestion query in order for the query to be reported as a success. - This parameter can be useful for ensuring search availability even for services with only one - replica. The default is 80. Default value is None. - :paramtype minimum_coverage: float - :keyword order_by: The comma-separated list of OData $orderby expressions by which to sort the - results. Each expression can be either a field name or a call to either the geo.distance() or - the search.score() functions. Each expression can be followed by asc to indicate ascending, or - desc to indicate descending. The default is ascending order. Ties will be broken by the match - scores of documents. If no $orderby is specified, the default sort order is descending by - document match score. There can be at most 32 $orderby clauses. Default value is None. - :paramtype order_by: str - :keyword search_fields: The comma-separated list of field names to search for the specified - search text. Target fields must be included in the specified suggester. Default value is None. - :paramtype search_fields: str - :keyword select: The comma-separated list of fields to retrieve. If unspecified, only the key - field will be included in the results. Default value is None. - :paramtype select: str - :keyword top: The number of suggestions to retrieve. This must be a value between 1 and 100. - The default is 5. Default value is None. - :paramtype top: int - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2._models.SuggestDocumentsResult: ... @overload - async def suggest( + async def _suggest_post( self, body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - :param body: Required. - :type body: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2._models.SuggestDocumentsResult: ... @overload - async def suggest( + async def _suggest_post( self, body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.SuggestDocumentsResult: - """Suggests documents in the index that match the given partial query text. - - :param body: Required. - :type body: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2._models.SuggestDocumentsResult: ... @distributed_trace_async - async def suggest( + async def _suggest_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -1314,7 +1017,7 @@ async def suggest( select: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models2.SuggestDocumentsResult: + ) -> _models2._models.SuggestDocumentsResult: """Suggests documents in the index that match the given partial query text. :param body: Is either a JSON type or a IO[bytes] type. Required. @@ -1368,7 +1071,7 @@ async def suggest( The default is 5. Default value is None. :paramtype top: int :return: SuggestDocumentsResult. The SuggestDocumentsResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.SuggestDocumentsResult + :rtype: ~azure.search.documents.models._models.SuggestDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1383,7 +1086,7 @@ async def suggest( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.SuggestDocumentsResult] = kwargs.pop("cls", None) + cls: ClsType[_models2._models.SuggestDocumentsResult] = kwargs.pop("cls", None) if body is _Unset: if search_text is _Unset: @@ -1411,7 +1114,7 @@ async def suggest( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_suggest_request( + _request = build_search_suggest_post_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -1445,7 +1148,9 @@ async def suggest( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.SuggestDocumentsResult, response.json()) + deserialized = _deserialize( + _models2._models.SuggestDocumentsResult, response.json() # pylint: disable=protected-access + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1453,88 +1158,41 @@ async def suggest( return deserialized # type: ignore @overload - def index_documents( + async def _index( self, batch: _models2.IndexDocumentsBatch, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> AsyncItemPaged["_models2.IndexingResult"]: - """Sends a batch of document write actions to the index. - - :param batch: The batch of index actions. Required. - :type batch: ~azure.search.documents.models.IndexDocumentsBatch - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2._models.IndexDocumentsResult: ... @overload - def index_documents( + async def _index( self, batch: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> AsyncItemPaged["_models2.IndexingResult"]: - """Sends a batch of document write actions to the index. - - :param batch: The batch of index actions. Required. - :type batch: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2._models.IndexDocumentsResult: ... @overload - def index_documents( + async def _index( self, batch: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> AsyncItemPaged["_models2.IndexingResult"]: - """Sends a batch of document write actions to the index. + ) -> _models2._models.IndexDocumentsResult: ... - :param batch: The batch of index actions. Required. - :type batch: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def index_documents( + @distributed_trace_async + async def _index( self, batch: Union[_models2.IndexDocumentsBatch, JSON, IO[bytes]], *, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models2.IndexingResult"]: + ) -> _models2._models.IndexDocumentsResult: """Sends a batch of document write actions to the index. :param batch: The batch of index actions. Is one of the following types: IndexDocumentsBatch, @@ -1544,16 +1202,10 @@ def index_documents( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: An iterator like instance of IndexingResult - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.IndexingResult] + :return: IndexDocumentsResult. The IndexDocumentsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.IndexDocumentsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[list[_models2.IndexingResult]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1561,6 +1213,13 @@ def index_documents( 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2._models.IndexDocumentsResult] = kwargs.pop("cls", None) + content_type = content_type or "application/json" _content = None if isinstance(batch, (IOBase, bytes)): @@ -1568,74 +1227,51 @@ def index_documents( else: _content = json.dumps(batch, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_index_documents_request( - index_name=self._config.index_name, - query_source_authorization=query_source_authorization, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.IndexingResult], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _request = build_search_index_request( + index_name=self._config.index_name, + query_source_authorization=query_source_authorization, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response - if response.status_code not in [200, 207]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + if response.status_code not in [200, 207]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.IndexDocumentsResult, response.json() # pylint: disable=protected-access + ) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return AsyncItemPaged(get_next, extract_data) + return deserialized # type: ignore - @distributed_trace - def _autocomplete_get( + @distributed_trace_async + async def _autocomplete_get( self, *, search_text: str, @@ -1650,7 +1286,7 @@ def _autocomplete_get( top: Optional[int] = None, query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models2.AutocompleteItem"]: + ) -> _models2._models.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. :keyword search_text: The incomplete term which should be auto-completed. Required. @@ -1693,16 +1329,10 @@ def _autocomplete_get( executed. This token is used to enforce security restrictions on documents. Default value is None. :paramtype query_source_authorization: str - :return: An iterator like instance of AutocompleteItem - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.models.AutocompleteItem] + :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping + :rtype: ~azure.search.documents.models._models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.AutocompleteItem]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1711,82 +1341,64 @@ def _autocomplete_get( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_search_autocomplete_get_request( - index_name=self._config.index_name, - search_text=search_text, - suggester_name=suggester_name, - autocomplete_mode=autocomplete_mode, - filter=filter, - use_fuzzy_matching=use_fuzzy_matching, - highlight_post_tag=highlight_post_tag, - highlight_pre_tag=highlight_pre_tag, - minimum_coverage=minimum_coverage, - search_fields=search_fields, - top=top, - query_source_authorization=query_source_authorization, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.AutocompleteItem], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models2._models.AutocompleteResult] = kwargs.pop("cls", None) + + _request = build_search_autocomplete_get_request( + index_name=self._config.index_name, + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + query_source_authorization=query_source_authorization, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - return pipeline_response + response = pipeline_response.http_response - return AsyncItemPaged(get_next, extract_data) + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - async def autocomplete( + async def _autocomplete_post( self, *, search_text: str, @@ -1802,110 +1414,28 @@ async def autocomplete( search_fields: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models2.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - :keyword search_text: The search text on which to base autocomplete results. Required. - :paramtype search_text: str - :keyword suggester_name: The name of the suggester as specified in the suggesters collection - that's part of the index definition. Required. - :paramtype suggester_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. Use - 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while producing - auto-completed terms. Known values are: "oneTerm", "twoTerms", and "oneTermWithContext". - Default value is None. - :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode - :keyword filter: An OData expression that filters the documents used to produce completed terms - for the Autocomplete result. Default value is None. - :paramtype filter: str - :keyword use_fuzzy_matching: A value indicating whether to use fuzzy matching for the - autocomplete query. Default is false. When set to true, the query will autocomplete terms even - if there's a substituted or missing character in the search text. While this provides a better - experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are - slower and consume more resources. Default value is None. - :paramtype use_fuzzy_matching: bool - :keyword highlight_post_tag: A string tag that is appended to hit highlights. Must be set with - highlightPreTag. If omitted, hit highlighting is disabled. Default value is None. - :paramtype highlight_post_tag: str - :keyword highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with - highlightPostTag. If omitted, hit highlighting is disabled. Default value is None. - :paramtype highlight_pre_tag: str - :keyword minimum_coverage: A number between 0 and 100 indicating the percentage of the index - that must be covered by an autocomplete query in order for the query to be reported as a - success. This parameter can be useful for ensuring search availability even for services with - only one replica. The default is 80. Default value is None. - :paramtype minimum_coverage: float - :keyword search_fields: The comma-separated list of field names to consider when querying for - auto-completed terms. Target fields must be included in the specified suggester. Default value - is None. - :paramtype search_fields: str - :keyword top: The number of auto-completed terms to retrieve. This must be a value between 1 - and 100. The default is 5. Default value is None. - :paramtype top: int - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2._models.AutocompleteResult: ... @overload - async def autocomplete( + async def _autocomplete_post( self, body: JSON, *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - :param body: Required. - :type body: JSON - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2._models.AutocompleteResult: ... @overload - async def autocomplete( + async def _autocomplete_post( self, body: IO[bytes], *, query_source_authorization: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models2.AutocompleteResult: - """Autocompletes incomplete query terms based on input text and matching terms in the index. - - :param body: Required. - :type body: IO[bytes] - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2._models.AutocompleteResult: ... @distributed_trace_async - async def autocomplete( + async def _autocomplete_post( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -1921,7 +1451,7 @@ async def autocomplete( search_fields: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> _models2.AutocompleteResult: + ) -> _models2._models.AutocompleteResult: """Autocompletes incomplete query terms based on input text and matching terms in the index. :param body: Is either a JSON type or a IO[bytes] type. Required. @@ -1968,7 +1498,7 @@ async def autocomplete( and 100. The default is 5. Default value is None. :paramtype top: int :return: AutocompleteResult. The AutocompleteResult is compatible with MutableMapping - :rtype: ~azure.search.documents.models.AutocompleteResult + :rtype: ~azure.search.documents.models._models.AutocompleteResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1983,7 +1513,7 @@ async def autocomplete( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.AutocompleteResult] = kwargs.pop("cls", None) + cls: ClsType[_models2._models.AutocompleteResult] = kwargs.pop("cls", None) if body is _Unset: if search_text is _Unset: @@ -2010,7 +1540,7 @@ async def autocomplete( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_autocomplete_request( + _request = build_search_autocomplete_post_request( index_name=self._config.index_name, query_source_authorization=query_source_authorization, content_type=content_type, @@ -2044,7 +1574,9 @@ async def autocomplete( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.AutocompleteResult, response.json()) + deserialized = _deserialize( + _models2._models.AutocompleteResult, response.json() # pylint: disable=protected-access + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index 4897838586fc..0348a3f89ba8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -1766,22 +1766,19 @@ def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models1.Syno return deserialized # type: ignore @distributed_trace - def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SynonymMap"]: + def _get_synonym_maps( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> _models1._models.ListSynonymMapsResult: """Lists all synonym maps available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SynonymMap - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SynonymMap] + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSynonymMapsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.SynonymMap]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1790,68 +1787,50 @@ def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> It } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_index_get_synonym_maps_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models1._models.ListSynonymMapsResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_index_get_synonym_maps_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.SynonymMap], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + response = pipeline_response.http_response - def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListSynonymMapsResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload def create_synonym_map( @@ -4868,25 +4847,19 @@ def get_data_source_connection( return deserialized # type: ignore @distributed_trace - def get_data_source_connections( + def _get_data_source_connections( self, *, select: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models1.SearchIndexerDataSourceConnection"]: + ) -> _models1._models.ListDataSourcesResult: """Lists all datasources available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SearchIndexerDataSourceConnection - :rtype: - ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListDataSourcesResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.SearchIndexerDataSourceConnection]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4895,68 +4868,50 @@ def get_data_source_connections( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_indexer_get_data_source_connections_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models1._models.ListDataSourcesResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_indexer_get_data_source_connections_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.SearchIndexerDataSourceConnection], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + response = pipeline_response.http_response - def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListDataSourcesResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload def create_data_source_connection( @@ -5775,22 +5730,17 @@ def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexe return deserialized # type: ignore @distributed_trace - def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models1.SearchIndexer"]: + def _get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1._models.ListIndexersResult: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SearchIndexer - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndexer] + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListIndexersResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.SearchIndexer]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -5799,68 +5749,50 @@ def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> ItemPa } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_indexer_get_indexers_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models1._models.ListIndexersResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_indexer_get_indexers_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.SearchIndexer], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + response = pipeline_response.http_response - def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListIndexersResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload def create_indexer( @@ -6409,25 +6341,17 @@ def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models1.SearchInde return deserialized # type: ignore @distributed_trace - def get_skillsets( - self, *, select: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models1.SearchIndexerSkillset"]: + def _get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _models1._models.ListSkillsetsResult: """List all skillsets in a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SearchIndexerSkillset - :rtype: - ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSkillsetsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.SearchIndexerSkillset]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -6436,68 +6360,50 @@ def get_skillsets( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_indexer_get_skillsets_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models1._models.ListSkillsetsResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_indexer_get_skillsets_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.SearchIndexerSkillset], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + response = pipeline_response.http_response - def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models2.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models1._models.ListSkillsetsResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload def create_skillset( diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 030ea9d91294..47741453811d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -416,24 +416,20 @@ async def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models return deserialized # type: ignore - @distributed_trace - def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SynonymMap"]: + @distributed_trace_async + async def _get_synonym_maps( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> _models2._models.ListSynonymMapsResult: """Lists all synonym maps available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SynonymMap - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SynonymMap] + :return: ListSynonymMapsResult. The ListSynonymMapsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSynonymMapsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.SynonymMap]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -442,68 +438,50 @@ def get_synonym_maps(self, *, select: Optional[str] = None, **kwargs: Any) -> As } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_index_get_synonym_maps_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models2._models.ListSynonymMapsResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_index_get_synonym_maps_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.SynonymMap], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) + response = pipeline_response.http_response - async def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListSynonymMapsResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return AsyncItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload async def create_synonym_map( @@ -3527,26 +3505,20 @@ async def get_data_source_connection( return deserialized # type: ignore - @distributed_trace - def get_data_source_connections( + @distributed_trace_async + async def _get_data_source_connections( self, *, select: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models2.SearchIndexerDataSourceConnection"]: + ) -> _models2._models.ListDataSourcesResult: """Lists all datasources available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SearchIndexerDataSourceConnection - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :return: ListDataSourcesResult. The ListDataSourcesResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListDataSourcesResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.SearchIndexerDataSourceConnection]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -3555,68 +3527,50 @@ def get_data_source_connections( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_indexer_get_data_source_connections_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models2._models.ListDataSourcesResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_indexer_get_data_source_connections_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.SearchIndexerDataSourceConnection], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) + response = pipeline_response.http_response - async def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListDataSourcesResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return AsyncItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload async def create_data_source_connection( @@ -4434,24 +4388,20 @@ async def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models2.Search return deserialized # type: ignore - @distributed_trace - def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models2.SearchIndexer"]: + @distributed_trace_async + async def _get_indexers( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> _models2._models.ListIndexersResult: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SearchIndexer - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndexer] + :return: ListIndexersResult. The ListIndexersResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListIndexersResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.SearchIndexer]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4460,68 +4410,50 @@ def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> AsyncI } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_indexer_get_indexers_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models2._models.ListIndexersResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_indexer_get_indexers_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.SearchIndexer], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) + response = pipeline_response.http_response - async def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListIndexersResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return AsyncItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload async def create_indexer( @@ -5069,26 +5001,20 @@ async def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models2.Sear return deserialized # type: ignore - @distributed_trace - def get_skillsets( + @distributed_trace_async + async def _get_skillsets( self, *, select: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models2.SearchIndexerSkillset"]: + ) -> _models2._models.ListSkillsetsResult: """List all skillsets in a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated list of JSON property names, or '*' for all properties. The default is all properties. Default value is None. :paramtype select: str - :return: An iterator like instance of SearchIndexerSkillset - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :return: ListSkillsetsResult. The ListSkillsetsResult is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models._models.ListSkillsetsResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.SearchIndexerSkillset]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -5097,68 +5023,50 @@ def get_skillsets( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_search_indexer_get_skillsets_request( - select=select, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models2._models.ListSkillsetsResult] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _request = build_search_indexer_get_skillsets_request( + select=select, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return _request + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.SearchIndexerSkillset], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) + response = pipeline_response.http_response - async def get_next(next_link=None): - _request = prepare_request(next_link) + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize(_models3.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models2._models.ListSkillsetsResult, response.json() # pylint: disable=protected-access ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) - raise HttpResponseError(response=response, model=error) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return AsyncItemPaged(get_next, extract_data) + return deserialized # type: ignore @overload async def create_skillset( diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 3317664cc66e..add0eaf62f01 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -5798,6 +5798,131 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.odata_type = "#Microsoft.Azure.Search.LimitTokenFilter" # type: ignore +class ListDataSourcesResult(_Model): + """Response from a List Datasources request. If successful, it includes the full definitions of + all datasources. + + :ivar data_sources: The datasources in the Search service. Required. + :vartype data_sources: + list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + """ + + data_sources: list["_models.SearchIndexerDataSourceConnection"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The datasources in the Search service. Required.""" + + @overload + def __init__( + self, + *, + data_sources: list["_models.SearchIndexerDataSourceConnection"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListIndexersResult(_Model): + """Response from a List Indexers request. If successful, it includes the full definitions of all + indexers. + + :ivar indexers: The indexers in the Search service. Required. + :vartype indexers: list[~azure.search.documents.indexes.models.SearchIndexer] + """ + + indexers: list["_models.SearchIndexer"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The indexers in the Search service. Required.""" + + @overload + def __init__( + self, + *, + indexers: list["_models.SearchIndexer"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListSkillsetsResult(_Model): + """Response from a list skillset request. If successful, it includes the full definitions of all + skillsets. + + :ivar skillsets: The skillsets defined in the Search service. Required. + :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + """ + + skillsets: list["_models.SearchIndexerSkillset"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The skillsets defined in the Search service. Required.""" + + @overload + def __init__( + self, + *, + skillsets: list["_models.SearchIndexerSkillset"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListSynonymMapsResult(_Model): + """Response from a List SynonymMaps request. If successful, it includes the full definitions of + all synonym maps. + + :ivar synonym_maps: The synonym maps in the Search service. Required. + :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] + """ + + synonym_maps: list["_models.SynonymMap"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The synonym maps in the Search service. Required.""" + + @overload + def __init__( + self, + *, + synonym_maps: list["_models.SynonymMap"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class LuceneStandardAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StandardAnalyzer"): """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop filter. diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 862c868a2f78..846bf6c3c217 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -15,7 +15,6 @@ from ._models import ( # type: ignore AutocompleteItem, - AutocompleteResult, DebugInfo, DocumentDebugInfo, ErrorAdditionalInfo, @@ -41,8 +40,6 @@ SearchScoreThreshold, SemanticDebugInfo, SingleVectorFieldResult, - SuggestDocumentsResult, - SuggestResult, TextResult, VectorQuery, VectorSimilarityThreshold, @@ -82,7 +79,6 @@ __all__ = [ "AutocompleteItem", - "AutocompleteResult", "DebugInfo", "DocumentDebugInfo", "ErrorAdditionalInfo", @@ -108,8 +104,6 @@ "SearchScoreThreshold", "SemanticDebugInfo", "SingleVectorFieldResult", - "SuggestDocumentsResult", - "SuggestResult", "TextResult", "VectorQuery", "VectorSimilarityThreshold", diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index be53ba951cea..279b344be8e8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -392,6 +392,37 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class IndexDocumentsResult(_Model): + """Response containing the status of operations for all documents in the indexing request. + + :ivar results: The list of status information for each document in the indexing request. + Required. + :vartype results: list[~azure.search.documents.models.IndexingResult] + """ + + results: list["_models.IndexingResult"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of status information for each document in the indexing request. Required.""" + + @overload + def __init__( + self, + *, + results: list["_models.IndexingResult"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class IndexingResult(_Model): """Status of an indexing operation for a single document. @@ -1317,13 +1348,13 @@ class SuggestDocumentsResult(_Model): """Response containing suggestion query results from an index. :ivar results: The sequence of results returned by the query. Required. - :vartype results: list[~azure.search.documents.models.SuggestResult] + :vartype results: list[~azure.search.documents.models._models.SuggestResult] :ivar coverage: A value indicating the percentage of the index that was included in the query, or null if minimumCoverage was not set in the request. :vartype coverage: float """ - results: list["_models.SuggestResult"] = rest_field( + results: list["_models._models.SuggestResult"] = rest_field( name="value", visibility=["read", "create", "update", "delete", "query"] ) """The sequence of results returned by the query. Required.""" @@ -1337,7 +1368,7 @@ class SuggestDocumentsResult(_Model): def __init__( self, *, - results: list["_models.SuggestResult"], + results: list["_models._models.SuggestResult"], coverage: Optional[float] = None, ) -> None: ... From 01470b1686e79c784d4d0c64a80073a74a34ec7a Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 09:40:48 -0700 Subject: [PATCH 18/40] updates --- .../search/documents/_operations/_patch.py | 35 + .../azure/search/documents/_patch.py | 3 +- .../documents/aio/_operations/_patch.py | 36 ++ .../documents/indexes/_operations/_patch.py | 598 ++++++++++++++++- .../indexes/aio/_operations/_patch.py | 599 +++++++++++++++++- .../azure/search/documents/models/_patch.py | 4 + 6 files changed, 1259 insertions(+), 16 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 962ff8e408b4..fdc214b30d95 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -16,6 +16,7 @@ from azure.core.tracing.decorator import distributed_trace from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated +from ..models._patch import RequestEntityTooLargeError from .. import models as _models @@ -322,6 +323,40 @@ def get_debug_info(self) -> Optional[_models.DebugInfo]: class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): """SearchClient operations mixin customizations.""" + @distributed_trace + def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + """Specify a document operations to perform as a batch. + + :param batch: A batch of document operations to perform. + :type batch: IndexDocumentsBatch + :return: List of IndexingResult + :rtype: list[IndexingResult] + + :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. + """ + return self._index_documents_actions(batch=batch, **kwargs) + + def _index_documents_actions(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + error_map = {413: RequestEntityTooLargeError} + try: + batch_response = self._client.documents.index(batch=batch, error_map=error_map, **kwargs) + return cast(List[_models.IndexingResult], batch_response.results) + except RequestEntityTooLargeError: + if len(batch.actions) == 1: + raise + pos = round(len(batch.actions) / 2) + batch_response_first_half = self._index_documents_actions(batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs) + if batch_response_first_half: + result_first_half = batch_response_first_half + else: + result_first_half = [] + batch_response_second_half = self._index_documents_actions(batch=_models.IndexDocumentsBatch(actions=batch.actions[pos:]), **kwargs) + if batch_response_second_half: + result_second_half = batch_response_second_half + else: + result_second_half = [] + result_first_half.extend(result_second_half) + return result_first_half def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Upload documents to the Azure search index. diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index 5a9bf72abbae..d8ce0297631f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -11,6 +11,7 @@ from azure.core import CaseInsensitiveEnumMeta from ._client import SearchClient as _SearchClient from ._operations._patch import SearchItemPaged +from .models._patch import RequestEntityTooLargeError class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -22,7 +23,6 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): DEFAULT_VERSION = ApiVersion.V2025_08_01_PREVIEW - class SearchClient(_SearchClient): """SearchClient customizations go here.""" @@ -35,6 +35,7 @@ def __init__(self, endpoint, index_name, credential, **kwargs): "SearchItemPaged", "ApiVersion", "DEFAULT_VERSION", + "RequestEntityTooLargeError", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 6519f58d1f21..2d66685dff49 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -21,6 +21,7 @@ _pack_continuation_token, _unpack_continuation_token, ) +from ...models._patch import RequestEntityTooLargeError from ... import models as _models @@ -180,6 +181,41 @@ async def get_debug_info(self) -> Optional[_models.DebugInfo]: class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): """Async SearchClient operations mixin customizations.""" + @distributed_trace_async + async def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + """Specify a document operations to perform as a batch. + + :param batch: A batch of document operations to perform. + :type batch: IndexDocumentsBatch + :return: List of IndexingResult + :rtype: list[IndexingResult] + + :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. + """ + return await self._index_documents_actions(batch=batch, **kwargs) + + async def _index_documents_actions(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + error_map = {413: RequestEntityTooLargeError} + + try: + batch_response = await self._client.documents.index(batch=batch, error_map=error_map, **kwargs) + return cast(List[_models.IndexingResult], batch_response.results) + except RequestEntityTooLargeError: + if len(batch.actions) == 1: + raise + pos = round(len(batch.actions) / 2) + batch_response_first_half = await self._index_documents_actions(batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs) + if batch_response_first_half: + result_first_half = batch_response_first_half + else: + result_first_half = [] + batch_response_second_half = await self._index_documents_actions(actions=actions[pos:], **kwargs) + if batch_response_second_half: + result_second_half = batch_response_second_half + else: + result_second_half = [] + result_first_half.extend(result_second_half) + return result_first_half async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Upload documents to the Azure search index. diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index a2be8396d5ff..1b0a75a08be4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -7,11 +7,13 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Iterator, cast, List, Sequence +from typing import Any, Iterator, cast, List, Sequence, Union, overload +from azure.core import MatchConditions from azure.core.paging import ItemPaged from azure.core.tracing.decorator import distributed_trace +from .. import models as _models from ._operations import ( _SearchIndexClientOperationsMixin as _SearchIndexClientOperationsMixinGenerated, _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, @@ -21,6 +23,365 @@ class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexClient.""" + @overload + def delete_synonym_map( + self, + synonym_map_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a synonym map. + + :param synonym_map_name: The name of the synonym map to delete. Required. + :type synonym_map_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_synonym_map( + self, + synonym_map: _models.SynonymMap, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a synonym map. + + :param synonym_map: The SynonymMap object to delete. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: Any) -> None: + """Deletes a synonym map. + + :param synonym_map_name: The name of the synonym map to delete. Required. + :type synonym_map_name: str + :param synonym_map: The SynonymMap object to delete. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SynonymMap): + synonym_map = args[0] + kwargs.setdefault("etag", synonym_map.e_tag) + return super().delete_synonym_map(synonym_map.name, **kwargs) + else: + return super().delete_synonym_map(*args, **kwargs) + + @overload + def delete_index( + self, + index_name: str, + *, + query_source_authorization: str | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. + + :param index_name: The name of the index to delete. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_index( + self, + index: _models.SearchIndex, + /, + *, + query_source_authorization: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. + + :param index: The SearchIndex object to delete. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> None: + """Deletes a search index and all the documents it contains. + + :param index_name: The name of the index to delete. Required. + :type index_name: str + :param index: The SearchIndex object to delete. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndex): + index = args[0] + kwargs.setdefault("etag", index.e_tag) + return super().delete_index(index.name, **kwargs) + else: + return super().delete_index(*args, **kwargs) + + @overload + def delete_alias( + self, + alias_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias_name: The name of the alias to delete. Required. + :type alias_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_alias( + self, + alias: _models.SearchAlias, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias: The SearchAlias object to delete. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias_name: The name of the alias to delete. Required. + :type alias_name: str + :param alias: The SearchAlias object to delete. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchAlias): + alias = args[0] + kwargs.setdefault("etag", alias.e_tag) + return super().delete_alias(alias.name, **kwargs) + else: + return super().delete_alias(*args, **kwargs) + + @overload + def delete_agent( + self, + agent_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge agent. + + :param agent_name: The name of the agent to delete. Required. + :type agent_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_agent( + self, + agent: _models.KnowledgeAgent, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge agent. + + :param agent: The KnowledgeAgent object to delete. Required. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any) -> None: + """Deletes a knowledge agent. + + :param agent_name: The name of the agent to delete. Required. + :type agent_name: str + :param agent: The KnowledgeAgent object to delete. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeAgent): + agent = args[0] + kwargs.setdefault("etag", agent.e_tag) + return super().delete_agent(agent.name, **kwargs) + else: + return super().delete_agent(*args, **kwargs) + + @overload + def delete_knowledge_source( + self, + source_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge source. + + :param source_name: The name of the knowledge source to delete. Required. + :type source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_knowledge_source( + self, + knowledge_source: _models.KnowledgeSource, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge source. + + :param knowledge_source: The KnowledgeSource object to delete. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_knowledge_source(self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any) -> None: + """Deletes a knowledge source. + + :param source_name: The name of the knowledge source to delete. Required. + :type source_name: str + :param knowledge_source: The KnowledgeSource object to delete. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeSource): + knowledge_source = args[0] + kwargs.setdefault("etag", knowledge_source.e_tag) + return super().delete_knowledge_source(knowledge_source.name, **kwargs) + else: + return super().delete_knowledge_source(*args, **kwargs) + @distributed_trace def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: """Lists the names of all indexes available for a search service. @@ -32,6 +393,22 @@ def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) return cast(ItemPaged[str], names) + @distributed_trace + def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a + comma-separated list of JSON property names, or '*' for all properties. The default is all + properties. + :paramtype select: str + :return: List of synonym maps + :rtype: list[~azure.search.documents.indexes.models.SynonymMap] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self._get_synonym_maps(**kwargs) + assert result.synonym_maps is not None # Hint for mypy + return result.synonym_maps + @distributed_trace def get_synonym_map_names(self, **kwargs: Any) -> List[str]: """Lists the names of all synonym maps available for a search service. @@ -40,7 +417,7 @@ def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :rtype: list[str] :raises ~azure.core.exceptions.HttpResponseError: """ - result = self.get_synonym_maps(**kwargs) + result = self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy return [x.name for x in result.synonym_maps] @@ -60,6 +437,215 @@ def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexerClient.""" + @overload + def delete_data_source_connection( + self, + data_source_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a data source connection. + + :param data_source_name: The name of the data source connection to delete. Required. + :type data_source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_data_source_connection( + self, + data_source: _models.SearchIndexerDataSourceConnection, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a data source connection. + + :param data_source: The SearchIndexerDataSourceConnection object to delete. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_data_source_connection( + self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any + ) -> None: + """Deletes a data source connection. + + :param data_source_name: The name of the data source connection to delete. Required. + :type data_source_name: str + :param data_source: The SearchIndexerDataSourceConnection object to delete. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): + data_source = args[0] + kwargs.setdefault("etag", data_source.e_tag) + return super().delete_data_source_connection(data_source.name, **kwargs) + else: + return super().delete_data_source_connection(*args, **kwargs) + + @overload + def delete_indexer( + self, + indexer_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes an indexer. + + :param indexer_name: The name of the indexer to delete. Required. + :type indexer_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_indexer( + self, + indexer: _models.SearchIndexer, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes an indexer. + + :param indexer: The SearchIndexer object to delete. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> None: + """Deletes an indexer. + + :param indexer_name: The name of the indexer to delete. Required. + :type indexer_name: str + :param indexer: The SearchIndexer object to delete. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexer): + indexer = args[0] + kwargs.setdefault("etag", indexer.e_tag) + return super().delete_indexer(indexer.name, **kwargs) + else: + return super().delete_indexer(*args, **kwargs) + + @overload + def delete_skillset( + self, + skillset_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a skillset. + + :param skillset_name: The name of the skillset to delete. Required. + :type skillset_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def delete_skillset( + self, + skillset: _models.SearchIndexerSkillset, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a skillset. + + :param skillset: The SearchIndexerSkillset object to delete. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any) -> None: + """Deletes a skillset. + + :param skillset_name: The name of the skillset to delete. Required. + :type skillset_name: str + :param skillset: The SearchIndexerSkillset object to delete. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerSkillset): + skillset = args[0] + kwargs.setdefault("etag", skillset.e_tag) + return super().delete_skillset(skillset.name, **kwargs) + else: + return super().delete_skillset(*args, **kwargs) + @distributed_trace def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: """Lists all indexer names available for a search service. @@ -89,9 +675,7 @@ def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: :rtype: list[str] """ - result = self.list_data_sources(**kwargs) - assert result.data_sources is not None # Hint for mypy - return [x.name for x in result.data_sources] + return self.get_data_source_connections(cls=lambda objs: [x.get("name") for x in objs], **kwargs) @distributed_trace def get_skillset_names(self, **kwargs: Any) -> List[str]: @@ -102,9 +686,7 @@ def get_skillset_names(self, **kwargs: Any) -> List[str]: :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. """ - result = self.list_skillsets(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [x.name for x in result.skillsets] + return self.get_skillsets(cls=lambda objs: [x.get("name") for x in objs], **kwargs) __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 899250840160..20cfa3ab3ac8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -7,12 +7,14 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, AsyncIterator, cast, List, Sequence +from typing import Any, AsyncIterator, cast, List, Sequence, Union, overload +from azure.core import MatchConditions from azure.core.async_paging import AsyncItemPaged from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from ... import models as _models from ._operations import ( _SearchIndexClientOperationsMixin as _SearchIndexClientOperationsMixinGenerated, _SearchIndexerClientOperationsMixin as _SearchIndexerClientOperationsMixinGenerated, @@ -22,6 +24,365 @@ class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexClient (async).""" + @overload + async def delete_synonym_map( + self, + synonym_map_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a synonym map. + + :param synonym_map_name: The name of the synonym map to delete. Required. + :type synonym_map_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_synonym_map( + self, + synonym_map: _models.SynonymMap, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a synonym map. + + :param synonym_map: The SynonymMap object to delete. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: Any) -> None: + """Deletes a synonym map. + + :param synonym_map_name: The name of the synonym map to delete. Required. + :type synonym_map_name: str + :param synonym_map: The SynonymMap object to delete. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SynonymMap): + synonym_map = args[0] + kwargs.setdefault("etag", synonym_map.e_tag) + return await super().delete_synonym_map(synonym_map.name, **kwargs) + else: + return await super().delete_synonym_map(*args, **kwargs) + + @overload + async def delete_index( + self, + index_name: str, + *, + query_source_authorization: str | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. + + :param index_name: The name of the index to delete. Required. + :type index_name: str + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_index( + self, + index: _models.SearchIndex, + /, + *, + query_source_authorization: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search index and all the documents it contains. + + :param index: The SearchIndex object to delete. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> None: + """Deletes a search index and all the documents it contains. + + :param index_name: The name of the index to delete. Required. + :type index_name: str + :param index: The SearchIndex object to delete. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndex): + index = args[0] + kwargs.setdefault("etag", index.e_tag) + return await super().delete_index(index.name, **kwargs) + else: + return await super().delete_index(*args, **kwargs) + + @overload + async def delete_alias( + self, + alias_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias_name: The name of the alias to delete. Required. + :type alias_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_alias( + self, + alias: _models.SearchAlias, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias: The SearchAlias object to delete. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> None: + """Deletes a search alias and its associated mapping to an index. + + :param alias_name: The name of the alias to delete. Required. + :type alias_name: str + :param alias: The SearchAlias object to delete. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchAlias): + alias = args[0] + kwargs.setdefault("etag", alias.e_tag) + return await super().delete_alias(alias.name, **kwargs) + else: + return await super().delete_alias(*args, **kwargs) + + @overload + async def delete_agent( + self, + agent_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge agent. + + :param agent_name: The name of the agent to delete. Required. + :type agent_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_agent( + self, + agent: _models.KnowledgeAgent, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge agent. + + :param agent: The KnowledgeAgent object to delete. Required. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any) -> None: + """Deletes a knowledge agent. + + :param agent_name: The name of the agent to delete. Required. + :type agent_name: str + :param agent: The KnowledgeAgent object to delete. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeAgent): + agent = args[0] + kwargs.setdefault("etag", agent.e_tag) + return await super().delete_agent(agent.name, **kwargs) + else: + return await super().delete_agent(*args, **kwargs) + + @overload + async def delete_knowledge_source( + self, + source_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge source. + + :param source_name: The name of the knowledge source to delete. Required. + :type source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_knowledge_source( + self, + knowledge_source: _models.KnowledgeSource, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a knowledge source. + + :param knowledge_source: The KnowledgeSource object to delete. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_knowledge_source(self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any) -> None: + """Deletes a knowledge source. + + :param source_name: The name of the knowledge source to delete. Required. + :type source_name: str + :param knowledge_source: The KnowledgeSource object to delete. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeSource): + knowledge_source = args[0] + kwargs.setdefault("etag", knowledge_source.e_tag) + return await super().delete_knowledge_source(knowledge_source.name, **kwargs) + else: + return await super().delete_knowledge_source(*args, **kwargs) + @distributed_trace def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: """Lists the names of all indexes available for a search service. @@ -33,17 +394,32 @@ def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) return cast(AsyncItemPaged[str], names) + @distributed_trace_async + async def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: + """Lists all synonym maps available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a + comma-separated list of JSON property names, or '*' for all properties. The default is all + properties. + :paramtype select: str + :return: List of synonym maps + :rtype: list[~azure.search.documents.indexes.models.SynonymMap] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self._get_synonym_maps(**kwargs) + assert result.synonym_maps is not None # Hint for mypy + return result.synonym_maps + @distributed_trace_async async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: """Lists the names of all synonym maps available for a search service. - :return: An async iterator of synonym map names - :rtype: AsyncIterator[str] + :return: List of synonym map names + :rtype: list[str] :raises ~azure.core.exceptions.HttpResponseError: """ - # Call the base get_synonym_maps method with select='name' to only retrieve names - result = await self.get_synonym_maps(select="name", **kwargs) - # Extract and yield just the names from the synonym_maps list + result = await self._get_synonym_maps(**kwargs) + assert result.synonym_maps is not None # Hint for mypy return [x.name for x in result.synonym_maps] @distributed_trace @@ -61,6 +437,215 @@ def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexerClient (async).""" + @overload + async def delete_data_source_connection( + self, + data_source_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a data source connection. + + :param data_source_name: The name of the data source connection to delete. Required. + :type data_source_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_data_source_connection( + self, + data_source: _models.SearchIndexerDataSourceConnection, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a data source connection. + + :param data_source: The SearchIndexerDataSourceConnection object to delete. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_data_source_connection( + self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any + ) -> None: + """Deletes a data source connection. + + :param data_source_name: The name of the data source connection to delete. Required. + :type data_source_name: str + :param data_source: The SearchIndexerDataSourceConnection object to delete. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): + data_source = args[0] + kwargs.setdefault("etag", data_source.e_tag) + return await super().delete_data_source_connection(data_source.name, **kwargs) + else: + return await super().delete_data_source_connection(*args, **kwargs) + + @overload + async def delete_indexer( + self, + indexer_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes an indexer. + + :param indexer_name: The name of the indexer to delete. Required. + :type indexer_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_indexer( + self, + indexer: _models.SearchIndexer, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes an indexer. + + :param indexer: The SearchIndexer object to delete. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> None: + """Deletes an indexer. + + :param indexer_name: The name of the indexer to delete. Required. + :type indexer_name: str + :param indexer: The SearchIndexer object to delete. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexer): + indexer = args[0] + kwargs.setdefault("etag", indexer.e_tag) + return await super().delete_indexer(indexer.name, **kwargs) + else: + return await super().delete_indexer(*args, **kwargs) + + @overload + async def delete_skillset( + self, + skillset_name: str, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a skillset. + + :param skillset_name: The name of the skillset to delete. Required. + :type skillset_name: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def delete_skillset( + self, + skillset: _models.SearchIndexerSkillset, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> None: + """Deletes a skillset. + + :param skillset: The SearchIndexerSkillset object to delete. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any) -> None: + """Deletes a skillset. + + :param skillset_name: The name of the skillset to delete. Required. + :type skillset_name: str + :param skillset: The SearchIndexerSkillset object to delete. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerSkillset): + skillset = args[0] + kwargs.setdefault("etag", skillset.e_tag) + return await super().delete_skillset(skillset.name, **kwargs) + else: + return await super().delete_skillset(*args, **kwargs) + @distributed_trace_async async def get_indexer_names(self, **kwargs) -> Sequence[str]: """Lists all indexer names available for a search service. @@ -80,7 +665,7 @@ async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: :rtype: list[str] """ - result = await self.list_data_sources(**kwargs) + result = await self.get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy return [x.name for x in result.data_sources] diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py index a98bbf2cbaf3..39d04971f5b2 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py @@ -8,12 +8,16 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ from typing import Any, Dict, List +from azure.core.exceptions import HttpResponseError from ._models import IndexDocumentsBatch as IndexDocumentsBatchGenerated from ._models import IndexAction from ._enums import IndexActionType +class RequestEntityTooLargeError(HttpResponseError): + """An error response with status code 413 - Request Entity Too Large""" + class IndexDocumentsBatch(IndexDocumentsBatchGenerated): """Contains a batch of document write actions to send to the index.""" From f17d6f9ff6d95ef2df476aeb9bf7fbb7a864aa23 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 09:48:10 -0700 Subject: [PATCH 19/40] update --- .../documents/indexes/_operations/_patch.py | 45 +++++++++++++++++-- .../indexes/aio/_operations/_patch.py | 44 ++++++++++++++++-- 2 files changed, 82 insertions(+), 7 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 1b0a75a08be4..0a97629396d1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -646,6 +646,45 @@ def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kw else: return super().delete_skillset(*args, **kwargs) + @overload + def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexers. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexers. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_indexers_operations.py + :start-after: [START list_indexer] + :end-before: [END list_indexer] + :language: python + :dedent: 4 + :caption: List all the SearchIndexers + """ + result = self._get_indexers(**kwargs) + assert result.indexers is not None # Hint for mypy + return result.indexers + @distributed_trace def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: """Lists all indexer names available for a search service. @@ -662,10 +701,8 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: :dedent: 4 :caption: List all the SearchIndexers """ - kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) - result = self.list_indexers(**kwargs) - assert result.indexers is not None # Hint for mypy - return [x.name for x in result.indexers] + result = self.get_indexers(**kwargs) + return [x.name for x in result] @distributed_trace def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 20cfa3ab3ac8..beac46c7b715 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -646,6 +646,45 @@ async def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset] else: return await super().delete_skillset(*args, **kwargs) + @overload + async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexers. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: + """Lists all indexers available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexers. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py + :start-after: [START list_indexer_async] + :end-before: [END list_indexer_async] + :language: python + :dedent: 4 + :caption: List all the SearchIndexers + """ + result = await self._get_indexers(**kwargs) + assert result.indexers is not None # Hint for mypy + return result.indexers + @distributed_trace_async async def get_indexer_names(self, **kwargs) -> Sequence[str]: """Lists all indexer names available for a search service. @@ -653,9 +692,8 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: :return: List of all the SearchIndexer names. :rtype: list[str] """ - result = await self.list_indexers(**kwargs) - assert result.indexers is not None # Hint for mypy - return [x.name for x in result.indexers] + result = await self.get_indexers(**kwargs) + return [x.name for x in result] @distributed_trace_async async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: From 22d26491799dd5e62bf826f00c37772a34132111 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 09:56:03 -0700 Subject: [PATCH 20/40] update --- .../documents/indexes/_operations/_patch.py | 43 +++++++++++++++++ .../indexes/aio/_operations/_patch.py | 46 ++++++++++++++++++- 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 0a97629396d1..a6c99b216cfe 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -704,6 +704,49 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: result = self.get_indexers(**kwargs) return [x.name for x in result] + @overload + def get_data_source_connections( + self, *, select: str | None = None, **kwargs: Any + ) -> List[_models.SearchIndexerDataSourceConnection]: + """Lists all data source connections available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the data source connections. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def get_data_source_connections( + self, **kwargs: Any + ) -> List[_models.SearchIndexerDataSourceConnection]: + """Lists all data source connections available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the data source connections. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_data_source_operations.py + :start-after: [START list_data_source_connection] + :end-before: [END list_data_source_connection] + :language: python + :dedent: 4 + :caption: List all the data source connections + """ + result = self._get_data_source_connections(**kwargs) + assert result.data_sources is not None # Hint for mypy + return result.data_sources + @distributed_trace def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: """Lists all data source connection names available for a search service. diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index beac46c7b715..0d3b14c8e537 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -695,6 +695,49 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: result = await self.get_indexers(**kwargs) return [x.name for x in result] + @overload + async def get_data_source_connections( + self, *, select: str | None = None, **kwargs: Any + ) -> List[_models.SearchIndexerDataSourceConnection]: + """Lists all data source connections available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the data source connections. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def get_data_source_connections( + self, **kwargs: Any + ) -> List[_models.SearchIndexerDataSourceConnection]: + """Lists all data source connections available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the data source connections. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_data_source_operations_async.py + :start-after: [START list_data_source_connection] + :end-before: [END list_data_source_connection] + :language: python + :dedent: 4 + :caption: List all the data source connections + """ + result = await self._get_data_source_connections(**kwargs) + assert result.data_sources is not None # Hint for mypy + return result.data_sources + @distributed_trace_async async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: """Lists all data source connection names available for a search service. @@ -704,8 +747,7 @@ async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_data_source_connections(**kwargs) - assert result.data_sources is not None # Hint for mypy - return [x.name for x in result.data_sources] + return [x.get("name") for x in result] @distributed_trace_async async def get_skillset_names(self, **kwargs) -> Sequence[str]: From 86f31adbe51a26a19f780b5f4f09b7883529883f Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 10:03:48 -0700 Subject: [PATCH 21/40] update --- .../documents/indexes/_operations/_patch.py | 33 ++++++++++++++++- .../indexes/aio/_operations/_patch.py | 35 +++++++++++++++++-- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index a6c99b216cfe..bf1044f58d9b 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -646,6 +646,36 @@ def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kw else: return super().delete_skillset(*args, **kwargs) + @overload + def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + """Lists all skillsets available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexerSkillsets. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + """Lists all skillsets available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexerSkillsets. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = self._get_skillsets(**kwargs) + assert result.skillsets is not None # Hint for mypy + return result.skillsets + @overload def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: """Lists all indexers available for a search service. @@ -766,7 +796,8 @@ def get_skillset_names(self, **kwargs: Any) -> List[str]: :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. """ - return self.get_skillsets(cls=lambda objs: [x.get("name") for x in objs], **kwargs) + result = self.get_skillsets(**kwargs) + return [x.get("name") for x in result] __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 0d3b14c8e537..8cd7e37a8cdd 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -646,6 +646,36 @@ async def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset] else: return await super().delete_skillset(*args, **kwargs) + @overload + async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + """Lists all skillsets available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexerSkillsets. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + """Lists all skillsets available for a search service. + + :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated + list of JSON property names, or '*' for all properties. The default is all properties. Default + value is None. + :paramtype select: str + :return: List of all the SearchIndexerSkillsets. + :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] + :raises ~azure.core.exceptions.HttpResponseError: + """ + result = await self._get_skillsets(**kwargs) + assert result.skillsets is not None # Hint for mypy + return result.skillsets + @overload async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: """Lists all indexers available for a search service. @@ -758,9 +788,8 @@ async def get_skillset_names(self, **kwargs) -> Sequence[str]: :raises ~azure.core.exceptions.HttpResponseError: If there is an error in the REST request. """ - result = await self.list_skillsets(**kwargs) - assert result.skillsets is not None # Hint for mypy - return [x.name for x in result.skillsets] + result = await self.get_skillsets(**kwargs) + return [x.get("name") for x in result] __all__: list[str] = [ From f032372badd7f872c61247b756555ce143288646 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 10:24:04 -0700 Subject: [PATCH 22/40] update --- .../search/documents/_operations/_patch.py | 155 ++++++++++++++++++ .../documents/aio/_operations/_patch.py | 155 ++++++++++++++++++ 2 files changed, 310 insertions(+) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index fdc214b30d95..fe457e8868db 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -792,6 +792,161 @@ def page_iterator_factory(continuation_token=None): return SearchItemPaged(page_iterator_factory) + @distributed_trace + def autocomplete( + self, + search_text: str, + suggester_name: str, + *, + autocomplete_mode: Optional[Union[str, _models.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> List[Dict[str, Any]]: + """Autocomplete incomplete search terms based on input text and matching terms in the index. + + :param str search_text: The search text on which to base autocomplete results. + :param str suggester_name: The name of the suggester as specified in the suggesters + collection that's part of the index definition. + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. + Use 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while + producing auto-completed terms. Known values are: "oneTerm", "twoTerms", and + "oneTermWithContext". + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword str filter: An OData expression that filters the documents used to produce completed + terms for the Autocomplete result. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. + :keyword str search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. + :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. + :return: List of autocomplete results. + :rtype: list[dict[str, Any]] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_autocomplete.py + :start-after: [START autocomplete_query] + :end-before: [END autocomplete_query] + :language: python + :dedent: 4 + :caption: Get autocomplete suggestions. + """ + # Call the generated _autocomplete_post method + response = self._autocomplete_post( + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + **kwargs, + ) + + assert response.results is not None # Hint for mypy + return response.results + + @distributed_trace + def suggest( + self, + search_text: str, + suggester_name: str, + *, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> List[Dict[str, Any]]: + """Get search suggestions for documents in the Azure search index. + + :param str search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. + :param str suggester_name: The name of the suggester as specified in the suggesters + collection that's part of the index definition. + :keyword str filter: An OData expression that filters the documents considered for suggestions. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. + :keyword str order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :keyword str search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. + :keyword str select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. + :keyword int top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. + :return: List of suggestion results. + :rtype: list[dict[str, Any]] + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_suggestions.py + :start-after: [START suggest] + :end-before: [END suggest] + :language: python + :dedent: 4 + :caption: Get search suggestions. + """ + # Call the generated _suggest_post method + response = self._suggest_post( + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + **kwargs, + ) + + assert response.results is not None # Hint for mypy + return response.results + __all__: list[str] = [ "_SearchClientOperationsMixin", "SearchItemPaged", diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 2d66685dff49..40bf8a4f7d07 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -581,6 +581,161 @@ def page_iterator_factory(continuation_token=None): # Return AsyncSearchItemPaged with the factory function return AsyncSearchItemPaged(page_iterator_factory) + @distributed_trace_async + async def autocomplete( + self, + search_text: str, + suggester_name: str, + *, + autocomplete_mode: Optional[Union[str, _models.AutocompleteMode]] = None, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + search_fields: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> List[Dict[str, Any]]: + """Autocomplete incomplete search terms based on input text and matching terms in the index. + + :param str search_text: The search text on which to base autocomplete results. + :param str suggester_name: The name of the suggester as specified in the suggesters + collection that's part of the index definition. + :keyword autocomplete_mode: Specifies the mode for Autocomplete. The default is 'oneTerm'. + Use 'twoTerms' to get shingles and 'oneTermWithContext' to use the current context while + producing auto-completed terms. Known values are: "oneTerm", "twoTerms", and + "oneTermWithContext". + :paramtype autocomplete_mode: str or ~azure.search.documents.models.AutocompleteMode + :keyword str filter: An OData expression that filters the documents used to produce completed + terms for the Autocomplete result. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + autocomplete query. Default is false. When set to true, the query will find terms even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are + slower and consume more resources. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting is disabled. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by an autocomplete query in order for the query to be reported as a + success. This parameter can be useful for ensuring search availability even for services with + only one replica. The default is 80. + :keyword str search_fields: The comma-separated list of field names to consider when querying for + auto-completed terms. Target fields must be included in the specified suggester. + :keyword int top: The number of auto-completed terms to retrieve. This must be a value between 1 + and 100. The default is 5. + :return: List of autocomplete results. + :rtype: list[dict[str, Any]] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_autocomplete_async.py + :start-after: [START autocomplete_query_async] + :end-before: [END autocomplete_query_async] + :language: python + :dedent: 4 + :caption: Get autocomplete suggestions. + """ + # Call the generated _autocomplete_post method + response = await self._autocomplete_post( + search_text=search_text, + suggester_name=suggester_name, + autocomplete_mode=autocomplete_mode, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + search_fields=search_fields, + top=top, + **kwargs, + ) + + assert response.results is not None # Hint for mypy + return response.results + + @distributed_trace_async + async def suggest( + self, + search_text: str, + suggester_name: str, + *, + filter: Optional[str] = None, + use_fuzzy_matching: Optional[bool] = None, + highlight_post_tag: Optional[str] = None, + highlight_pre_tag: Optional[str] = None, + minimum_coverage: Optional[float] = None, + order_by: Optional[str] = None, + search_fields: Optional[str] = None, + select: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> List[Dict[str, Any]]: + """Get search suggestions for documents in the Azure search index. + + :param str search_text: The search text to use to suggest documents. Must be at least 1 + character, and no more than 100 characters. + :param str suggester_name: The name of the suggester as specified in the suggesters + collection that's part of the index definition. + :keyword str filter: An OData expression that filters the documents considered for suggestions. + :keyword bool use_fuzzy_matching: A value indicating whether to use fuzzy matching for the + suggestion query. Default is false. When set to true, the query will find suggestions even if + there's a substituted or missing character in the search text. While this provides a better + experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are + slower and consume more resources. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with + highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with + highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index + that must be covered by a suggestion query in order for the query to be reported as a success. + This parameter can be useful for ensuring search availability even for services with only one + replica. The default is 80. + :keyword str order_by: The comma-separated list of OData $orderby expressions by which to sort the + results. Each expression can be either a field name or a call to either the geo.distance() or + the search.score() functions. Each expression can be followed by asc to indicate ascending, or + desc to indicate descending. The default is ascending order. Ties will be broken by the match + scores of documents. If no $orderby is specified, the default sort order is descending by + document match score. There can be at most 32 $orderby clauses. + :keyword str search_fields: The comma-separated list of field names to search for the specified + search text. Target fields must be included in the specified suggester. + :keyword str select: The comma-separated list of fields to retrieve. If unspecified, only the key + field will be included in the results. + :keyword int top: The number of suggestions to retrieve. This must be a value between 1 and 100. + The default is 5. + :return: List of suggestion results. + :rtype: list[dict[str, Any]] + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_suggestions_async.py + :start-after: [START suggest] + :end-before: [END suggest] + :language: python + :dedent: 4 + :caption: Get search suggestions. + """ + # Call the generated _suggest_post method + response = await self._suggest_post( + search_text=search_text, + suggester_name=suggester_name, + filter=filter, + use_fuzzy_matching=use_fuzzy_matching, + highlight_post_tag=highlight_post_tag, + highlight_pre_tag=highlight_pre_tag, + minimum_coverage=minimum_coverage, + order_by=order_by, + search_fields=search_fields, + select=select, + top=top, + **kwargs, + ) + + assert response.results is not None # Hint for mypy + return response.results + __all__: list[str] = [ "_SearchClientOperationsMixin", From 75591514f488a37b3c3027d57ea6257dac980f35 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 11:28:42 -0700 Subject: [PATCH 23/40] update --- .../azure/search/documents/_operations/_patch.py | 6 +++--- .../azure/search/documents/aio/_operations/_patch.py | 6 +++--- .../azure/search/documents/indexes/_operations/_patch.py | 7 ++++--- .../search/documents/indexes/aio/_operations/_patch.py | 6 +++--- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index fe457e8868db..386ac3c6b7a1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -201,10 +201,10 @@ def __init__(self, client, initial_request: _models.SearchRequest, kwargs, conti def _get_next_cb(self, continuation_token): if continuation_token is None: - return self._client.search_post(body=self._initial_request, **self._kwargs) + return self._client._search_post(body=self._initial_request, **self._kwargs) _next_link, next_page_request = _unpack_continuation_token(continuation_token) - return self._client.search_post(body=next_page_request, **self._kwargs) + return self._client._search_post(body=next_page_request, **self._kwargs) def _extract_data_cb(self, response: _models.SearchDocumentsResult): continuation_token = _pack_continuation_token(response, api_version=self._api_version) @@ -339,7 +339,7 @@ def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> def _index_documents_actions(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: error_map = {413: RequestEntityTooLargeError} try: - batch_response = self._client.documents.index(batch=batch, error_map=error_map, **kwargs) + batch_response = self._index(batch=batch, error_map=error_map, **kwargs) return cast(List[_models.IndexingResult], batch_response.results) except RequestEntityTooLargeError: if len(batch.actions) == 1: diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 40bf8a4f7d07..2c71b9202879 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -54,10 +54,10 @@ def __init__(self, client, initial_request: _models.SearchRequest, kwargs, conti async def _get_next_cb(self, continuation_token): if continuation_token is None: - return await self._client.search_post(body=self._initial_request, **self._kwargs) + return await self._client._search_post(body=self._initial_request, **self._kwargs) _next_link, next_page_request = _unpack_continuation_token(continuation_token) - return await self._client.search_post(body=next_page_request, **self._kwargs) + return await self._client._search_post(body=next_page_request, **self._kwargs) async def _extract_data_cb(self, response: _models.SearchDocumentsResult): continuation_token = _pack_continuation_token(response, api_version=self._api_version) @@ -198,7 +198,7 @@ async def _index_documents_actions(self, batch: _models.IndexDocumentsBatch, **k error_map = {413: RequestEntityTooLargeError} try: - batch_response = await self._client.documents.index(batch=batch, error_map=error_map, **kwargs) + batch_response = await self._index(batch=batch, error_map=error_map, **kwargs) return cast(List[_models.IndexingResult], batch_response.results) except RequestEntityTooLargeError: if len(batch.actions) == 1: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index bf1044f58d9b..ebc5ffe84a50 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -419,7 +419,7 @@ def get_synonym_map_names(self, **kwargs: Any) -> List[str]: """ result = self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy - return [x.name for x in result.synonym_maps] + return [x.name for x in result] @distributed_trace def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: @@ -785,7 +785,8 @@ def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: :rtype: list[str] """ - return self.get_data_source_connections(cls=lambda objs: [x.get("name") for x in objs], **kwargs) + result = self.get_data_source_connections(**kwargs) + return [x.name for x in result] @distributed_trace def get_skillset_names(self, **kwargs: Any) -> List[str]: @@ -797,7 +798,7 @@ def get_skillset_names(self, **kwargs: Any) -> List[str]: """ result = self.get_skillsets(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 8cd7e37a8cdd..47965f14dd71 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -420,7 +420,7 @@ async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: """ result = await self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy - return [x.name for x in result.synonym_maps] + return [x.name for x in result] @distributed_trace def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: @@ -777,7 +777,7 @@ async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_data_source_connections(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @distributed_trace_async async def get_skillset_names(self, **kwargs) -> Sequence[str]: @@ -789,7 +789,7 @@ async def get_skillset_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_skillsets(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] __all__: list[str] = [ From df166111e42655e83578e7547b21468659ef44fb Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 11:30:07 -0700 Subject: [PATCH 24/40] update --- .../azure/search/documents/indexes/_operations/_patch.py | 3 +-- .../azure/search/documents/indexes/aio/_operations/_patch.py | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index ebc5ffe84a50..b129abd193fd 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -417,8 +417,7 @@ def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :rtype: list[str] :raises ~azure.core.exceptions.HttpResponseError: """ - result = self._get_synonym_maps(**kwargs) - assert result.synonym_maps is not None # Hint for mypy + result = self.get_synonym_maps(**kwargs) return [x.name for x in result] @distributed_trace diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 47965f14dd71..e4b8c7d452e1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -418,8 +418,7 @@ async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :rtype: list[str] :raises ~azure.core.exceptions.HttpResponseError: """ - result = await self._get_synonym_maps(**kwargs) - assert result.synonym_maps is not None # Hint for mypy + result = await self.get_synonym_maps(**kwargs) return [x.name for x in result] @distributed_trace From c185564be3dea845a3478edb2f0b7fc06463e45a Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 13:15:26 -0700 Subject: [PATCH 25/40] update --- .../search/documents/_operations/_patch.py | 26 ++++--- .../azure/search/documents/_patch.py | 1 + .../documents/aio/_operations/_patch.py | 22 ++++-- .../documents/indexes/_operations/_patch.py | 28 +++---- .../indexes/aio/_operations/_patch.py | 28 +++---- .../documents/indexes/models/_models.py | 20 +++++ .../search/documents/indexes/models/_patch.py | 77 ------------------- .../azure/search/documents/models/_patch.py | 1 + 8 files changed, 83 insertions(+), 120 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 386ac3c6b7a1..be5216368a6f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -323,6 +323,7 @@ def get_debug_info(self) -> Optional[_models.DebugInfo]: class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): """SearchClient operations mixin customizations.""" + @distributed_trace def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: """Specify a document operations to perform as a batch. @@ -336,21 +337,28 @@ def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> """ return self._index_documents_actions(batch=batch, **kwargs) - def _index_documents_actions(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + def _index_documents_actions( + self, batch: _models.IndexDocumentsBatch, **kwargs: Any + ) -> List[_models.IndexingResult]: error_map = {413: RequestEntityTooLargeError} try: batch_response = self._index(batch=batch, error_map=error_map, **kwargs) - return cast(List[_models.IndexingResult], batch_response.results) + typed_result = [cast(_models.IndexingResult, x) for x in batch_response.results] + return typed_result except RequestEntityTooLargeError: if len(batch.actions) == 1: raise pos = round(len(batch.actions) / 2) - batch_response_first_half = self._index_documents_actions(batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs) + batch_response_first_half = self._index_documents_actions( + batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs + ) if batch_response_first_half: result_first_half = batch_response_first_half else: result_first_half = [] - batch_response_second_half = self._index_documents_actions(batch=_models.IndexDocumentsBatch(actions=batch.actions[pos:]), **kwargs) + batch_response_second_half = self._index_documents_actions( + batch=_models.IndexDocumentsBatch(actions=batch.actions[pos:]), **kwargs + ) if batch_response_second_half: result_second_half = batch_response_second_half else: @@ -383,7 +391,7 @@ def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models batch.add_upload_actions(documents) result = self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Delete documents from the Azure search index. @@ -411,7 +419,7 @@ def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models batch.add_delete_actions(documents) result = self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Merge documents in the Azure search index. @@ -439,7 +447,7 @@ def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models. batch.add_merge_actions(documents) result = self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Merge or upload documents to the Azure search index. @@ -466,7 +474,7 @@ def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> Lis batch.add_merge_or_upload_actions(documents) result = self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result @distributed_trace def search( @@ -791,7 +799,6 @@ def page_iterator_factory(continuation_token=None): # Return SearchItemPaged with the factory function return SearchItemPaged(page_iterator_factory) - @distributed_trace def autocomplete( self, @@ -947,6 +954,7 @@ def suggest( assert response.results is not None # Hint for mypy return response.results + __all__: list[str] = [ "_SearchClientOperationsMixin", "SearchItemPaged", diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index d8ce0297631f..d4fcc286556c 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -23,6 +23,7 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): DEFAULT_VERSION = ApiVersion.V2025_08_01_PREVIEW + class SearchClient(_SearchClient): """SearchClient customizations go here.""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 2c71b9202879..3e1f3b4da393 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -181,6 +181,7 @@ async def get_debug_info(self) -> Optional[_models.DebugInfo]: class _SearchClientOperationsMixin(_SearchClientOperationsMixinGenerated): """Async SearchClient operations mixin customizations.""" + @distributed_trace_async async def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: """Specify a document operations to perform as a batch. @@ -194,17 +195,22 @@ async def index_documents(self, batch: _models.IndexDocumentsBatch, **kwargs: An """ return await self._index_documents_actions(batch=batch, **kwargs) - async def _index_documents_actions(self, batch: _models.IndexDocumentsBatch, **kwargs: Any) -> List[_models.IndexingResult]: + async def _index_documents_actions( + self, batch: _models.IndexDocumentsBatch, **kwargs: Any + ) -> List[_models.IndexingResult]: error_map = {413: RequestEntityTooLargeError} try: batch_response = await self._index(batch=batch, error_map=error_map, **kwargs) - return cast(List[_models.IndexingResult], batch_response.results) + typed_result = [cast(_models.IndexingResult, x) for x in batch_response.results] + return typed_result except RequestEntityTooLargeError: if len(batch.actions) == 1: raise pos = round(len(batch.actions) / 2) - batch_response_first_half = await self._index_documents_actions(batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs) + batch_response_first_half = await self._index_documents_actions( + batch=_models.IndexDocumentsBatch(actions=batch.actions[:pos]), **kwargs + ) if batch_response_first_half: result_first_half = batch_response_first_half else: @@ -242,7 +248,7 @@ async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ batch.add_upload_actions(documents) result = await self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Delete documents from the Azure search index. @@ -270,7 +276,7 @@ async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ batch.add_delete_actions(documents) result = await self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Merge documents in the Azure search index. @@ -298,7 +304,7 @@ async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_m batch.add_merge_actions(documents) result = await self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models.IndexingResult]: """Merge or upload documents to the Azure search index. @@ -325,7 +331,7 @@ async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) batch.add_merge_or_upload_actions(documents) result = await self.index_documents(batch, **kwargs) - return cast(List[_models.IndexingResult], result.results) + return result @distributed_trace_async async def search( @@ -368,7 +374,7 @@ async def search( query_rewrites_count: Optional[int] = None, debug: Optional[Union[str, _models.QueryDebugMode]] = None, hybrid_search: Optional[_models.HybridSearch] = None, - **kwargs: Any + **kwargs: Any, ) -> AsyncSearchItemPaged[Dict]: """Search the Azure search index for documents. diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index b129abd193fd..4d9248905c27 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -390,7 +390,7 @@ def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: :rtype: ~azure.core.paging.ItemPaged[str] :raises ~azure.core.exceptions.HttpResponseError: """ - names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) + names = self.list_indexes(cls=lambda objs: [x.get("name") for x in objs], **kwargs) return cast(ItemPaged[str], names) @distributed_trace @@ -407,7 +407,8 @@ def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: """ result = self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy - return result.synonym_maps + typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + return typed_result @distributed_trace def get_synonym_map_names(self, **kwargs: Any) -> List[str]: @@ -418,7 +419,7 @@ def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :raises ~azure.core.exceptions.HttpResponseError: """ result = self.get_synonym_maps(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] @distributed_trace def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: @@ -429,7 +430,7 @@ def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. """ - names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) + names = self.list_aliases(cls=lambda objs: [x.get("name") for x in objs], **kwargs) return cast(ItemPaged[str], names) @@ -673,7 +674,8 @@ def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: """ result = self._get_skillsets(**kwargs) assert result.skillsets is not None # Hint for mypy - return result.skillsets + typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + return typed_result @overload def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: @@ -712,7 +714,8 @@ def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: """ result = self._get_indexers(**kwargs) assert result.indexers is not None # Hint for mypy - return result.indexers + typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + return typed_result @distributed_trace def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: @@ -731,7 +734,7 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: :caption: List all the SearchIndexers """ result = self.get_indexers(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] @overload def get_data_source_connections( @@ -750,9 +753,7 @@ def get_data_source_connections( ... @distributed_trace - def get_data_source_connections( - self, **kwargs: Any - ) -> List[_models.SearchIndexerDataSourceConnection]: + def get_data_source_connections(self, **kwargs: Any) -> List[_models.SearchIndexerDataSourceConnection]: """Lists all data source connections available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -774,7 +775,8 @@ def get_data_source_connections( """ result = self._get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy - return result.data_sources + typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + return typed_result @distributed_trace def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: @@ -785,7 +787,7 @@ def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: """ result = self.get_data_source_connections(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] @distributed_trace def get_skillset_names(self, **kwargs: Any) -> List[str]: @@ -797,7 +799,7 @@ def get_skillset_names(self, **kwargs: Any) -> List[str]: """ result = self.get_skillsets(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index e4b8c7d452e1..fe218abf5f5d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -391,7 +391,7 @@ def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: :rtype: ~azure.core.async_paging.AsyncItemPaged[str] :raises ~azure.core.exceptions.HttpResponseError: """ - names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) + names = self.list_indexes(cls=lambda objs: [x.get("name") for x in objs], **kwargs) return cast(AsyncItemPaged[str], names) @distributed_trace_async @@ -408,7 +408,8 @@ async def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: """ result = await self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy - return result.synonym_maps + typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + return typed_result @distributed_trace_async async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: @@ -419,7 +420,7 @@ async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :raises ~azure.core.exceptions.HttpResponseError: """ result = await self.get_synonym_maps(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] @distributed_trace def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: @@ -429,7 +430,7 @@ def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: :rtype: ~azure.core.async_paging.AsyncItemPaged[str] :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. """ - names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) + names = self.list_aliases(cls=lambda objs: [x.get("name") for x in objs], **kwargs) return cast(AsyncItemPaged[str], names) @@ -673,7 +674,8 @@ async def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkills """ result = await self._get_skillsets(**kwargs) assert result.skillsets is not None # Hint for mypy - return result.skillsets + typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + return typed_result @overload async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: @@ -712,7 +714,8 @@ async def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: """ result = await self._get_indexers(**kwargs) assert result.indexers is not None # Hint for mypy - return result.indexers + typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + return typed_result @distributed_trace_async async def get_indexer_names(self, **kwargs) -> Sequence[str]: @@ -722,7 +725,7 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: :rtype: list[str] """ result = await self.get_indexers(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] @overload async def get_data_source_connections( @@ -741,9 +744,7 @@ async def get_data_source_connections( ... @distributed_trace_async - async def get_data_source_connections( - self, **kwargs: Any - ) -> List[_models.SearchIndexerDataSourceConnection]: + async def get_data_source_connections(self, **kwargs: Any) -> List[_models.SearchIndexerDataSourceConnection]: """Lists all data source connections available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -765,7 +766,8 @@ async def get_data_source_connections( """ result = await self._get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy - return result.data_sources + typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + return typed_result @distributed_trace_async async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: @@ -776,7 +778,7 @@ async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_data_source_connections(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] @distributed_trace_async async def get_skillset_names(self, **kwargs) -> Sequence[str]: @@ -788,7 +790,7 @@ async def get_skillset_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_skillsets(**kwargs) - return [x.name for x in result] + return [x.get("name") for x in result] __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index add0eaf62f01..a02289860450 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -8396,6 +8396,8 @@ class SearchIndexerDataSourceConnection(_Model): unaffected. Encryption with customer-managed keys is not available for free search services, and is only available for paid services created on or after January 1, 2019.""" + __flattened_items = ["connection_string"] + @overload def __init__( self, @@ -8422,7 +8424,25 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.credentials is None: + return None + return getattr(self.credentials, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.credentials is None: + self.credentials = self._attr_to_rest_field["credentials"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) class SearchIndexerDataUserAssignedIdentity( diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index 46021bd0f65e..237339026148 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -514,89 +514,12 @@ def ComplexField( return _SearchField(**result) -class SearchIndexerDataSourceConnection(_SearchIndexerDataSourceConnection): - """Represents a datasource connection definition, which can be used to configure an indexer. - - All required parameters must be populated in order to send to Azure. - - :ivar name: Required. The name of the datasource connection. - :vartype name: str - :ivar description: The description of the datasource connection. - :vartype description: str - :ivar type: Required. The type of the datasource connection. Possible values include: "azuresql", - "cosmosdb", "azureblob", "azuretable", "mysql", "adlsgen2". - :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType - :ivar connection_string: The connection string for the datasource connection. - :vartype connection_string: str - :ivar container: Required. The data container for the datasource connection. - :vartype container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer - :ivar identity: An explicit managed identity to use for this datasource. If not specified and - the connection string is a managed identity, the system-assigned managed identity is used. If - not specified, the value remains unchanged. If "none" is specified, the value of this property - is cleared. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar indexer_permission_options: Ingestion options with various types of permission data. - :vartype indexer_permission_options: list[str or - ~azure.search.documents.indexes.models.IndexerPermissionOption] - :ivar data_change_detection_policy: The data change detection policy for the datasource connection. - :vartype data_change_detection_policy: ~azure.search.documents.models.DataChangeDetectionPolicy - :ivar data_deletion_detection_policy: The data deletion detection policy for the datasource connection. - :vartype data_deletion_detection_policy: - ~azure.search.documents.models.DataDeletionDetectionPolicy - :ivar e_tag: The ETag of the data source. - :vartype e_tag: str - :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. - This key is used to provide an additional level of encryption-at-rest for your datasource - definition when you want full assurance that no one, not even Microsoft, can decrypt your data - source definition in Azure Cognitive Search. Once you have encrypted your data source - definition, it will always remain encrypted. Azure Cognitive Search will ignore attempts to set - this property to null. You can change this property as needed if you want to rotate your - encryption key; Your datasource definition will be unaffected. Encryption with customer-managed - keys is not available for free search services, and is only available for paid services created - on or after January 1, 2019. - :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - """ - - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - type: str, - connection_string: str, - container: SearchIndexerDataContainer, - identity: Optional[SearchIndexerDataIdentity] = None, - indexer_permission_options: Optional[List[Union[str, IndexerPermissionOption]]] = None, - data_change_detection_policy: Optional[DataChangeDetectionPolicy] = None, - data_deletion_detection_policy: Optional[DataDeletionDetectionPolicy] = None, - e_tag: Optional[str] = None, - encryption_key: Optional[SearchResourceEncryptionKey] = None, - **kwargs - ): - credentials = DataSourceCredentials(connection_string=connection_string) - super().__init__( - name=name, - description=description, - type=type, - credentials=credentials, - container=container, - data_change_detection_policy=data_change_detection_policy, - data_deletion_detection_policy=data_deletion_detection_policy, - e_tag=e_tag, - encryption_key=encryption_key, - identity=identity, - indexer_permission_options=indexer_permission_options, - **kwargs - ) - - __all__: list[str] = [ "SearchField", "SearchFieldDataType", "SimpleField", "SearchableField", "ComplexField", - "SearchIndexerDataSourceConnection", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py index 39d04971f5b2..cbac73e992ac 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py @@ -18,6 +18,7 @@ class RequestEntityTooLargeError(HttpResponseError): """An error response with status code 413 - Request Entity Too Large""" + class IndexDocumentsBatch(IndexDocumentsBatchGenerated): """Contains a batch of document write actions to send to the index.""" From 614c9de5f6d2a3acc23c1ae9be5b0f0476a72ff6 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 13:53:14 -0700 Subject: [PATCH 26/40] update --- .../azure/search/documents/_operations/_patch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index be5216368a6f..13ec7e6f9c0a 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -22,7 +22,7 @@ def _convert_search_result(result: _models.SearchResult) -> Dict[str, Any]: """Convert SearchResult model to dictionary with @search.* metadata.""" - ret = dict(result.additional_properties) if result.additional_properties else {} + ret = dict(result) if result.score is not None: ret["@search.score"] = result.score if result.reranker_score is not None: From 4775bb4423743f27dca568c0b698c842a4663360 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 16:12:47 -0700 Subject: [PATCH 27/40] updates --- .../search/documents/_operations/_patch.py | 18 +- .../indexes/_operations/_operations.py | 645 ++-------------- .../documents/indexes/_operations/_patch.py | 686 ++++++++++++++++- .../indexes/aio/_operations/_operations.py | 645 ++-------------- .../indexes/aio/_operations/_patch.py | 690 +++++++++++++++++- .../test_search_client_search_live_async.py | 9 +- .../test_search_index_client_live_async.py | 4 +- .../tests/search_service_preparer.py | 6 +- .../tests/test_search_client_search_live.py | 9 +- .../tests/test_search_index_client_live.py | 4 +- .../tests/test_serialization.py | 10 +- 11 files changed, 1506 insertions(+), 1220 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 13ec7e6f9c0a..36e9477b51fd 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -23,18 +23,12 @@ def _convert_search_result(result: _models.SearchResult) -> Dict[str, Any]: """Convert SearchResult model to dictionary with @search.* metadata.""" ret = dict(result) - if result.score is not None: - ret["@search.score"] = result.score - if result.reranker_score is not None: - ret["@search.reranker_score"] = result.reranker_score - if result.highlights is not None: - ret["@search.highlights"] = result.highlights - if result.captions is not None: - ret["@search.captions"] = result.captions - if result.document_debug_info is not None: - ret["@search.document_debug_info"] = result.document_debug_info - if result.reranker_boosted_score is not None: - ret["@search.reranker_boosted_score"] = result.reranker_boosted_score + ret["@search.score"] = result.score + ret["@search.reranker_score"] = result.reranker_score + ret["@search.highlights"] = result.highlights + ret["@search.captions"] = result.captions + ret["@search.document_debug_info"] = result.document_debug_info + ret["@search.reranker_boosted_score"] = result.reranker_boosted_score return ret diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index 0348a3f89ba8..011d46b73c16 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -1092,7 +1092,7 @@ def build_search_indexer_run_indexer_request(indexer_name: str, **kwargs: Any) - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_indexer_create_or_update_request( # pylint: disable=name-too-long +def build_search_indexer_create_or_update_indexer_request( # pylint: disable=name-too-long indexer_name: str, *, skip_indexer_reset_requirement_for_cache: Optional[bool] = None, @@ -1449,7 +1449,7 @@ class _SearchIndexClientOperationsMixin( # pylint: disable=too-many-public-meth ): @overload - def create_or_update_synonym_map( + def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: _models1.SynonymMap, @@ -1458,28 +1458,9 @@ def create_or_update_synonym_map( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SynonymMap: ... @overload - def create_or_update_synonym_map( + def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: JSON, @@ -1488,28 +1469,9 @@ def create_or_update_synonym_map( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SynonymMap: ... @overload - def create_or_update_synonym_map( + def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: IO[bytes], @@ -1518,28 +1480,10 @@ def create_or_update_synonym_map( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SynonymMap: ... @distributed_trace - def create_or_update_synonym_map( + def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: Union[_models1.SynonymMap, JSON, IO[bytes]], @@ -1954,7 +1898,7 @@ def create_synonym_map( return deserialized # type: ignore @overload - def create_or_update_index( + def _create_or_update_index( self, index_name: str, index: _models1.SearchIndex, @@ -1965,38 +1909,9 @@ def create_or_update_index( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndex: ... @overload - def create_or_update_index( + def _create_or_update_index( self, index_name: str, index: JSON, @@ -2007,38 +1922,9 @@ def create_or_update_index( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: JSON - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndex: ... @overload - def create_or_update_index( + def _create_or_update_index( self, index_name: str, index: IO[bytes], @@ -2049,38 +1935,10 @@ def create_or_update_index( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SearchIndex: ... @distributed_trace - def create_or_update_index( + def _create_or_update_index( self, index_name: str, index: Union[_models1.SearchIndex, JSON, IO[bytes]], @@ -2782,7 +2640,7 @@ def analyze_text( return deserialized # type: ignore @overload - def create_or_update_alias( + def _create_or_update_alias( self, alias_name: str, alias: _models1.SearchAlias, @@ -2791,28 +2649,9 @@ def create_or_update_alias( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchAlias: ... @overload - def create_or_update_alias( + def _create_or_update_alias( self, alias_name: str, alias: JSON, @@ -2821,28 +2660,9 @@ def create_or_update_alias( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchAlias: ... @overload - def create_or_update_alias( + def _create_or_update_alias( self, alias_name: str, alias: IO[bytes], @@ -2851,28 +2671,10 @@ def create_or_update_alias( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SearchAlias: ... @distributed_trace - def create_or_update_alias( + def _create_or_update_alias( self, alias_name: str, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], @@ -3302,7 +3104,7 @@ def create_alias(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kw return deserialized # type: ignore @overload - def create_or_update_agent( + def _create_or_update_agent( self, agent_name: str, knowledge_agent: _models1.KnowledgeAgent, @@ -3311,28 +3113,9 @@ def create_or_update_agent( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.KnowledgeAgent: ... @overload - def create_or_update_agent( + def _create_or_update_agent( self, agent_name: str, knowledge_agent: JSON, @@ -3341,28 +3124,9 @@ def create_or_update_agent( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.KnowledgeAgent: ... @overload - def create_or_update_agent( + def _create_or_update_agent( self, agent_name: str, knowledge_agent: IO[bytes], @@ -3371,28 +3135,10 @@ def create_or_update_agent( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.KnowledgeAgent: ... @distributed_trace - def create_or_update_agent( + def _create_or_update_agent( self, agent_name: str, knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], @@ -3826,7 +3572,7 @@ def create_agent( return deserialized # type: ignore @overload - def create_or_update_knowledge_source( + def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: _models1.KnowledgeSource, @@ -3835,28 +3581,9 @@ def create_or_update_knowledge_source( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.KnowledgeSource: ... @overload - def create_or_update_knowledge_source( + def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: JSON, @@ -3865,28 +3592,9 @@ def create_or_update_knowledge_source( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.KnowledgeSource: ... @overload - def create_or_update_knowledge_source( + def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: IO[bytes], @@ -3895,28 +3603,10 @@ def create_or_update_knowledge_source( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.KnowledgeSource: ... @distributed_trace - def create_or_update_knowledge_source( + def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: Union[_models1.KnowledgeSource, JSON, IO[bytes]], @@ -4501,7 +4191,7 @@ class _SearchIndexerClientOperationsMixin( # pylint: disable=too-many-public-me ): @overload - def create_or_update_data_source_connection( + def _create_or_update_data_source_connection( self, data_source_name: str, data_source: _models1.SearchIndexerDataSourceConnection, @@ -4511,32 +4201,9 @@ def create_or_update_data_source_connection( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexerDataSourceConnection: - """Creates a new datasource or updates a datasource if it already exists. - - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible - with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndexerDataSourceConnection: ... @overload - def create_or_update_data_source_connection( + def _create_or_update_data_source_connection( self, data_source_name: str, data_source: JSON, @@ -4546,32 +4213,9 @@ def create_or_update_data_source_connection( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexerDataSourceConnection: - """Creates a new datasource or updates a datasource if it already exists. - - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible - with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndexerDataSourceConnection: ... @overload - def create_or_update_data_source_connection( + def _create_or_update_data_source_connection( self, data_source_name: str, data_source: IO[bytes], @@ -4581,36 +4225,14 @@ def create_or_update_data_source_connection( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexerDataSourceConnection: - """Creates a new datasource or updates a datasource if it already exists. - - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible - with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SearchIndexerDataSourceConnection: ... @distributed_trace @api_version_validation( params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - def create_or_update_data_source_connection( + def _create_or_update_data_source_connection( self, data_source_name: str, data_source: Union[_models1.SearchIndexerDataSourceConnection, JSON, IO[bytes]], @@ -5370,7 +4992,7 @@ def run_indexer(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disa return cls(pipeline_response, None, {}) # type: ignore @overload - def create_or_update( + def _create_or_update_indexer( self, indexer_name: str, indexer: _models1.SearchIndexer, @@ -5381,34 +5003,9 @@ def create_or_update( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndexer: ... @overload - def create_or_update( + def _create_or_update_indexer( self, indexer_name: str, indexer: JSON, @@ -5419,34 +5016,9 @@ def create_or_update( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndexer: ... @overload - def create_or_update( + def _create_or_update_indexer( self, indexer_name: str, indexer: IO[bytes], @@ -5457,31 +5029,7 @@ def create_or_update( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SearchIndexer: ... @distributed_trace @api_version_validation( @@ -5493,7 +5041,7 @@ def create_or_update( }, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - def create_or_update( + def _create_or_update_indexer( self, indexer_name: str, indexer: Union[_models1.SearchIndexer, JSON, IO[bytes]], @@ -5554,7 +5102,7 @@ def create_or_update( else: _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_indexer_create_or_update_request( + _request = build_search_indexer_create_or_update_indexer_request( indexer_name=indexer_name, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, @@ -5977,7 +5525,7 @@ def get_indexer_status(self, indexer_name: str, **kwargs: Any) -> _models1.Searc return deserialized # type: ignore @overload - def create_or_update_skillset( + def _create_or_update_skillset( self, skillset_name: str, skillset: _models1.SearchIndexerSkillset, @@ -5988,35 +5536,9 @@ def create_or_update_skillset( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndexerSkillset: ... @overload - def create_or_update_skillset( + def _create_or_update_skillset( self, skillset_name: str, skillset: JSON, @@ -6027,35 +5549,9 @@ def create_or_update_skillset( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models1.SearchIndexerSkillset: ... @overload - def create_or_update_skillset( + def _create_or_update_skillset( self, skillset_name: str, skillset: IO[bytes], @@ -6066,32 +5562,7 @@ def create_or_update_skillset( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models1.SearchIndexerSkillset: ... @distributed_trace @api_version_validation( @@ -6103,7 +5574,7 @@ def create_or_update_skillset( }, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - def create_or_update_skillset( + def _create_or_update_skillset( self, skillset_name: str, skillset: Union[_models1.SearchIndexerSkillset, JSON, IO[bytes]], diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 4d9248905c27..4e7b799a7ae9 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -92,6 +92,78 @@ def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: An else: return super().delete_synonym_map(*args, **kwargs) + @overload + def create_or_update_synonym_map( + self, + synonym_map_name: str, + synonym_map: _models.SynonymMap, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_synonym_map( + self, + synonym_map: _models.SynonymMap, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map: The SynonymMap object to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: Any) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The SynonymMap object to create or update. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SynonymMap): + synonym_map = args[0] + kwargs.setdefault("etag", synonym_map.e_tag) + return self._create_or_update_synonym_map(synonym_map.name, synonym_map, prefer="return=representation", **kwargs) + else: + return self._create_or_update_synonym_map(*args, prefer="return=representation", **kwargs) + @overload def delete_index( self, @@ -175,6 +247,184 @@ def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> else: return super().delete_index(*args, **kwargs) + @overload + def create_or_update_index( + self, + index_name: str, + index: _models.SearchIndex, + *, + allow_index_downtime: bool | None = None, + query_source_authorization: str | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_index( + self, + index: _models.SearchIndex, + /, + *, + allow_index_downtime: bool | None = None, + query_source_authorization: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index: The SearchIndex object to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The SearchIndex object to create or update. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndex): + index = args[0] + kwargs.setdefault("etag", index.e_tag) + return self._create_or_update_index(index.name, index, prefer="return=representation", **kwargs) + else: + return self._create_or_update_index(*args, prefer="return=representation", **kwargs) + + @overload + def create_or_update_alias( + self, + alias_name: str, + alias: _models.SearchAlias, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_alias( + self, + alias: _models.SearchAlias, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias: The SearchAlias object to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The SearchAlias object to create or update. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchAlias): + alias = args[0] + kwargs.setdefault("etag", alias.e_tag) + return self._create_or_update_alias(alias.name, alias, prefer="return=representation", **kwargs) + else: + return self._create_or_update_alias(*args, prefer="return=representation", **kwargs) + @overload def delete_alias( self, @@ -313,6 +563,154 @@ def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any) else: return super().delete_agent(*args, **kwargs) + @overload + def create_or_update_agent( + self, + agent_name: str, + agent: _models.KnowledgeAgent, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent: The definition of the agent to create or update. Required. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_agent( + self, + agent: _models.KnowledgeAgent, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent: The KnowledgeAgent object to create or update. Required. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_agent( + self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any + ) -> _models.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent: The KnowledgeAgent object to create or update. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeAgent): + agent = args[0] + kwargs.setdefault("etag", agent.e_tag) + return self._create_or_update_agent(agent.name, agent, prefer="return=representation", **kwargs) + else: + return self._create_or_update_agent(*args, prefer="return=representation", **kwargs) + + @overload + def create_or_update_knowledge_source( + self, + source_name: str, + knowledge_source: _models.KnowledgeSource, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_knowledge_source( + self, + knowledge_source: _models.KnowledgeSource, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param knowledge_source: The KnowledgeSource object to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_knowledge_source( + self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The KnowledgeSource object to create or update. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeSource): + knowledge_source = args[0] + kwargs.setdefault("etag", knowledge_source.e_tag) + return self._create_or_update_knowledge_source(knowledge_source.name, knowledge_source, prefer="return=representation", **kwargs) + else: + return self._create_or_update_knowledge_source(*args, prefer="return=representation", **kwargs) + @overload def delete_knowledge_source( self, @@ -390,7 +788,7 @@ def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: :rtype: ~azure.core.paging.ItemPaged[str] :raises ~azure.core.exceptions.HttpResponseError: """ - names = self.list_indexes(cls=lambda objs: [x.get("name") for x in objs], **kwargs) + names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) return cast(ItemPaged[str], names) @distributed_trace @@ -419,7 +817,7 @@ def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :raises ~azure.core.exceptions.HttpResponseError: """ result = self.get_synonym_maps(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @distributed_trace def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: @@ -430,7 +828,7 @@ def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. """ - names = self.list_aliases(cls=lambda objs: [x.get("name") for x in objs], **kwargs) + names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) return cast(ItemPaged[str], names) @@ -508,6 +906,91 @@ def delete_data_source_connection( else: return super().delete_data_source_connection(*args, **kwargs) + @overload + def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: _models.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source_name: The name of the data source connection. Required. + :type data_source_name: str + :param data_source: The definition of the data source connection to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_data_source_connection( + self, + data_source: _models.SearchIndexerDataSourceConnection, + /, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source: The SearchIndexerDataSourceConnection object to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_data_source_connection( + self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source_name: The name of the data source connection. Required. + :type data_source_name: str + :param data_source: The SearchIndexerDataSourceConnection object to create or update. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): + data_source = args[0] + kwargs.setdefault("etag", data_source.e_tag) + return self._create_or_update_data_source_connection(data_source.name, data_source, prefer="return=representation", **kwargs) + else: + return self._create_or_update_data_source_connection(*args, prefer="return=representation", **kwargs) + @overload def delete_indexer( self, @@ -577,6 +1060,100 @@ def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any else: return super().delete_indexer(*args, **kwargs) + @overload + def create_or_update_indexer( + self, + indexer_name: str, + indexer: _models.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_indexer( + self, + indexer: _models.SearchIndexer, + /, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer: The SearchIndexer object to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The SearchIndexer object to create or update. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexer): + indexer = args[0] + kwargs.setdefault("etag", indexer.e_tag) + return self._create_or_update_indexer(indexer.name, indexer, prefer="return=representation", **kwargs) + else: + return self._create_or_update_indexer(*args, prefer="return=representation", **kwargs) + @overload def delete_skillset( self, @@ -646,6 +1223,103 @@ def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kw else: return super().delete_skillset(*args, **kwargs) + @overload + def create_or_update_skillset( + self, + skillset_name: str, + skillset: _models.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + def create_or_update_skillset( + self, + skillset: _models.SearchIndexerSkillset, + /, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset: The SearchIndexerSkillset object to create or update. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace + def create_or_update_skillset( + self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The SearchIndexerSkillset object to create or update. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerSkillset): + skillset = args[0] + kwargs.setdefault("etag", skillset.e_tag) + return self._create_or_update_skillset(skillset.name, skillset, prefer="return=representation", **kwargs) + else: + return self._create_or_update_skillset(*args, prefer="return=representation", **kwargs) + @overload def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: """Lists all skillsets available for a search service. @@ -734,7 +1408,7 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: :caption: List all the SearchIndexers """ result = self.get_indexers(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @overload def get_data_source_connections( @@ -787,7 +1461,7 @@ def get_data_source_connection_names(self, **kwargs: Any) -> Sequence[str]: """ result = self.get_data_source_connections(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @distributed_trace def get_skillset_names(self, **kwargs: Any) -> List[str]: @@ -799,7 +1473,7 @@ def get_skillset_names(self, **kwargs: Any) -> List[str]: """ result = self.get_skillsets(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 47741453811d..8a221b3e6f8a 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -69,7 +69,7 @@ build_search_indexer_create_data_source_connection_request, build_search_indexer_create_indexer_request, build_search_indexer_create_or_update_data_source_connection_request, - build_search_indexer_create_or_update_request, + build_search_indexer_create_or_update_indexer_request, build_search_indexer_create_or_update_skillset_request, build_search_indexer_create_skillset_request, build_search_indexer_delete_data_source_connection_request, @@ -100,7 +100,7 @@ class _SearchIndexClientOperationsMixin( # pylint: disable=too-many-public-meth ): @overload - async def create_or_update_synonym_map( + async def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: _models2.SynonymMap, @@ -109,28 +109,9 @@ async def create_or_update_synonym_map( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SynonymMap: ... @overload - async def create_or_update_synonym_map( + async def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: JSON, @@ -139,28 +120,9 @@ async def create_or_update_synonym_map( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SynonymMap: ... @overload - async def create_or_update_synonym_map( + async def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: IO[bytes], @@ -169,28 +131,10 @@ async def create_or_update_synonym_map( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap. The SynonymMap is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SynonymMap: ... @distributed_trace_async - async def create_or_update_synonym_map( + async def _create_or_update_synonym_map( self, synonym_map_name: str, synonym_map: Union[_models2.SynonymMap, JSON, IO[bytes]], @@ -605,7 +549,7 @@ async def create_synonym_map( return deserialized # type: ignore @overload - async def create_or_update_index( + async def _create_or_update_index( self, index_name: str, index: _models2.SearchIndex, @@ -616,38 +560,9 @@ async def create_or_update_index( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndex: ... @overload - async def create_or_update_index( + async def _create_or_update_index( self, index_name: str, index: JSON, @@ -658,38 +573,9 @@ async def create_or_update_index( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: JSON - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndex: ... @overload - async def create_or_update_index( + async def _create_or_update_index( self, index_name: str, index: IO[bytes], @@ -700,38 +586,10 @@ async def create_or_update_index( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: IO[bytes] - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex. The SearchIndex is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SearchIndex: ... @distributed_trace_async - async def create_or_update_index( + async def _create_or_update_index( self, index_name: str, index: Union[_models2.SearchIndex, JSON, IO[bytes]], @@ -1436,7 +1294,7 @@ async def analyze_text( return deserialized # type: ignore @overload - async def create_or_update_alias( + async def _create_or_update_alias( self, alias_name: str, alias: _models2.SearchAlias, @@ -1445,28 +1303,9 @@ async def create_or_update_alias( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchAlias: ... @overload - async def create_or_update_alias( + async def _create_or_update_alias( self, alias_name: str, alias: JSON, @@ -1475,28 +1314,9 @@ async def create_or_update_alias( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchAlias: ... @overload - async def create_or_update_alias( + async def _create_or_update_alias( self, alias_name: str, alias: IO[bytes], @@ -1505,28 +1325,10 @@ async def create_or_update_alias( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias. The SearchAlias is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SearchAlias: ... @distributed_trace_async - async def create_or_update_alias( + async def _create_or_update_alias( self, alias_name: str, alias: Union[_models2.SearchAlias, JSON, IO[bytes]], @@ -1959,7 +1761,7 @@ async def create_alias( return deserialized # type: ignore @overload - async def create_or_update_agent( + async def _create_or_update_agent( self, agent_name: str, knowledge_agent: _models2.KnowledgeAgent, @@ -1968,28 +1770,9 @@ async def create_or_update_agent( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.KnowledgeAgent: ... @overload - async def create_or_update_agent( + async def _create_or_update_agent( self, agent_name: str, knowledge_agent: JSON, @@ -1998,28 +1781,9 @@ async def create_or_update_agent( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.KnowledgeAgent: ... @overload - async def create_or_update_agent( + async def _create_or_update_agent( self, agent_name: str, knowledge_agent: IO[bytes], @@ -2028,28 +1792,10 @@ async def create_or_update_agent( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Required. - :type knowledge_agent: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.KnowledgeAgent: ... @distributed_trace_async - async def create_or_update_agent( + async def _create_or_update_agent( self, agent_name: str, knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], @@ -2484,7 +2230,7 @@ async def create_agent( return deserialized # type: ignore @overload - async def create_or_update_knowledge_source( + async def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: _models2.KnowledgeSource, @@ -2493,28 +2239,9 @@ async def create_or_update_knowledge_source( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.KnowledgeSource: ... @overload - async def create_or_update_knowledge_source( + async def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: JSON, @@ -2523,28 +2250,9 @@ async def create_or_update_knowledge_source( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.KnowledgeSource: ... @overload - async def create_or_update_knowledge_source( + async def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: IO[bytes], @@ -2553,28 +2261,10 @@ async def create_or_update_knowledge_source( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeSource: - """Creates a new knowledge source or updates an knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource. The KnowledgeSource is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.KnowledgeSource: ... @distributed_trace_async - async def create_or_update_knowledge_source( + async def _create_or_update_knowledge_source( self, source_name: str, knowledge_source: Union[_models2.KnowledgeSource, JSON, IO[bytes]], @@ -3160,7 +2850,7 @@ class _SearchIndexerClientOperationsMixin( # pylint: disable=too-many-public-me ): @overload - async def create_or_update_data_source_connection( + async def _create_or_update_data_source_connection( self, data_source_name: str, data_source: _models2.SearchIndexerDataSourceConnection, @@ -3170,32 +2860,9 @@ async def create_or_update_data_source_connection( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSourceConnection: - """Creates a new datasource or updates a datasource if it already exists. - - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible - with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndexerDataSourceConnection: ... @overload - async def create_or_update_data_source_connection( + async def _create_or_update_data_source_connection( self, data_source_name: str, data_source: JSON, @@ -3205,32 +2872,9 @@ async def create_or_update_data_source_connection( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSourceConnection: - """Creates a new datasource or updates a datasource if it already exists. - - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible - with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndexerDataSourceConnection: ... @overload - async def create_or_update_data_source_connection( + async def _create_or_update_data_source_connection( self, data_source_name: str, data_source: IO[bytes], @@ -3240,36 +2884,14 @@ async def create_or_update_data_source_connection( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerDataSourceConnection: - """Creates a new datasource or updates a datasource if it already exists. - - :param data_source_name: The name of the datasource. Required. - :type data_source_name: str - :param data_source: The definition of the datasource to create or update. Required. - :type data_source: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection. The SearchIndexerDataSourceConnection is compatible - with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SearchIndexerDataSourceConnection: ... @distributed_trace_async @api_version_validation( params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - async def create_or_update_data_source_connection( + async def _create_or_update_data_source_connection( self, data_source_name: str, data_source: Union[_models2.SearchIndexerDataSourceConnection, JSON, IO[bytes]], @@ -4029,7 +3651,7 @@ async def run_indexer(self, indexer_name: str, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @overload - async def create_or_update( + async def _create_or_update_indexer( self, indexer_name: str, indexer: _models2.SearchIndexer, @@ -4040,34 +3662,9 @@ async def create_or_update( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndexer: ... @overload - async def create_or_update( + async def _create_or_update_indexer( self, indexer_name: str, indexer: JSON, @@ -4078,34 +3675,9 @@ async def create_or_update( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndexer: ... @overload - async def create_or_update( + async def _create_or_update_indexer( self, indexer_name: str, indexer: IO[bytes], @@ -4116,31 +3688,7 @@ async def create_or_update( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer. The SearchIndexer is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SearchIndexer: ... @distributed_trace_async @api_version_validation( @@ -4152,7 +3700,7 @@ async def create_or_update( }, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - async def create_or_update( + async def _create_or_update_indexer( self, indexer_name: str, indexer: Union[_models2.SearchIndexer, JSON, IO[bytes]], @@ -4213,7 +3761,7 @@ async def create_or_update( else: _content = json.dumps(indexer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_indexer_create_or_update_request( + _request = build_search_indexer_create_or_update_indexer_request( indexer_name=indexer_name, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, @@ -4638,7 +4186,7 @@ async def get_indexer_status(self, indexer_name: str, **kwargs: Any) -> _models2 return deserialized # type: ignore @overload - async def create_or_update_skillset( + async def _create_or_update_skillset( self, skillset_name: str, skillset: _models2.SearchIndexerSkillset, @@ -4649,35 +4197,9 @@ async def create_or_update_skillset( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndexerSkillset: ... @overload - async def create_or_update_skillset( + async def _create_or_update_skillset( self, skillset_name: str, skillset: JSON, @@ -4688,35 +4210,9 @@ async def create_or_update_skillset( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: JSON - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models2.SearchIndexerSkillset: ... @overload - async def create_or_update_skillset( + async def _create_or_update_skillset( self, skillset_name: str, skillset: IO[bytes], @@ -4727,32 +4223,7 @@ async def create_or_update_skillset( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: IO[bytes] - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset. The SearchIndexerSkillset is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models2.SearchIndexerSkillset: ... @distributed_trace_async @api_version_validation( @@ -4764,7 +4235,7 @@ async def create_or_update_skillset( }, api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], ) - async def create_or_update_skillset( + async def _create_or_update_skillset( self, skillset_name: str, skillset: Union[_models2.SearchIndexerSkillset, JSON, IO[bytes]], diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index fe218abf5f5d..fe048dfcb575 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -93,6 +93,80 @@ async def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwar else: return await super().delete_synonym_map(*args, **kwargs) + @overload + async def create_or_update_synonym_map( + self, + synonym_map_name: str, + synonym_map: _models.SynonymMap, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The definition of the synonym map to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_synonym_map( + self, + synonym_map: _models.SynonymMap, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map: The SynonymMap object to create or update. Required. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_synonym_map( + self, *args: Union[str, _models.SynonymMap], **kwargs: Any + ) -> _models.SynonymMap: + """Creates a new synonym map or updates a synonym map if it already exists. + + :param synonym_map_name: The name of the synonym map. Required. + :type synonym_map_name: str + :param synonym_map: The SynonymMap object to create or update. + :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SynonymMap + :rtype: ~azure.search.documents.indexes.models.SynonymMap + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SynonymMap): + synonym_map = args[0] + kwargs.setdefault("etag", synonym_map.e_tag) + return await self._create_or_update_synonym_map(synonym_map.name, synonym_map, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_synonym_map(*args, prefer="return=representation", **kwargs) + @overload async def delete_index( self, @@ -176,6 +250,186 @@ async def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: A else: return await super().delete_index(*args, **kwargs) + @overload + async def create_or_update_index( + self, + index_name: str, + index: _models.SearchIndex, + *, + allow_index_downtime: bool | None = None, + query_source_authorization: str | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The definition of the index to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_index( + self, + index: _models.SearchIndex, + /, + *, + allow_index_downtime: bool | None = None, + query_source_authorization: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index: The SearchIndex object to create or update. Required. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_index( + self, *args: Union[str, _models.SearchIndex], **kwargs: Any + ) -> _models.SearchIndex: + """Creates a new search index or updates an index if it already exists. + + :param index_name: The name of the index. Required. + :type index_name: str + :param index: The SearchIndex object to create or update. + :type index: ~azure.search.documents.indexes.models.SearchIndex + :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + to be added to an index by taking the index offline for at least a few seconds. This + temporarily causes indexing and query requests to fail. Performance and write availability of + the index can be impaired for several minutes after the index is updated, or longer for very + large indexes. Default value is None. + :paramtype allow_index_downtime: bool + :keyword query_source_authorization: Token identifying the user for which the query is being + executed. This token is used to enforce security restrictions on documents. Default value is + None. + :paramtype query_source_authorization: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndex + :rtype: ~azure.search.documents.indexes.models.SearchIndex + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndex): + index = args[0] + kwargs.setdefault("etag", index.e_tag) + return await self._create_or_update_index(index.name, index, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_index(*args, prefer="return=representation", **kwargs) + + @overload + async def create_or_update_alias( + self, + alias_name: str, + alias: _models.SearchAlias, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The definition of the alias to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_alias( + self, + alias: _models.SearchAlias, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias: The SearchAlias object to create or update. Required. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> _models.SearchAlias: + """Creates a new search alias or updates an alias if it already exists. + + :param alias_name: The name of the alias. Required. + :type alias_name: str + :param alias: The SearchAlias object to create or update. + :type alias: ~azure.search.documents.indexes.models.SearchAlias + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchAlias + :rtype: ~azure.search.documents.indexes.models.SearchAlias + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchAlias): + alias = args[0] + kwargs.setdefault("etag", alias.e_tag) + return await self._create_or_update_alias(alias.name, alias, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_alias(*args, prefer="return=representation", **kwargs) + @overload async def delete_alias( self, @@ -314,6 +568,154 @@ async def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs else: return await super().delete_agent(*args, **kwargs) + @overload + async def create_or_update_agent( + self, + agent_name: str, + agent: _models.KnowledgeAgent, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent: The definition of the agent to create or update. Required. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_agent( + self, + agent: _models.KnowledgeAgent, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent: The KnowledgeAgent object to create or update. Required. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_agent( + self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any + ) -> _models.KnowledgeAgent: + """Creates a new agent or updates an agent if it already exists. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent: The KnowledgeAgent object to create or update. + :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeAgent + :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeAgent): + agent = args[0] + kwargs.setdefault("etag", agent.e_tag) + return await self._create_or_update_agent(agent.name, agent, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_agent(*args, prefer="return=representation", **kwargs) + + @overload + async def create_or_update_knowledge_source( + self, + source_name: str, + knowledge_source: _models.KnowledgeSource, + *, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The definition of the knowledge source to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_knowledge_source( + self, + knowledge_source: _models.KnowledgeSource, + /, + *, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param knowledge_source: The KnowledgeSource object to create or update. Required. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_knowledge_source( + self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any + ) -> _models.KnowledgeSource: + """Creates a new knowledge source or updates a knowledge source if it already exists. + + :param source_name: The name of the knowledge source. Required. + :type source_name: str + :param knowledge_source: The KnowledgeSource object to create or update. + :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KnowledgeSource + :rtype: ~azure.search.documents.indexes.models.KnowledgeSource + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.KnowledgeSource): + knowledge_source = args[0] + kwargs.setdefault("etag", knowledge_source.e_tag) + return await self._create_or_update_knowledge_source(knowledge_source.name, knowledge_source, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_knowledge_source(*args, prefer="return=representation", **kwargs) + @overload async def delete_knowledge_source( self, @@ -391,7 +793,7 @@ def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: :rtype: ~azure.core.async_paging.AsyncItemPaged[str] :raises ~azure.core.exceptions.HttpResponseError: """ - names = self.list_indexes(cls=lambda objs: [x.get("name") for x in objs], **kwargs) + names = self.list_indexes(cls=lambda objs: [x.name for x in objs], **kwargs) return cast(AsyncItemPaged[str], names) @distributed_trace_async @@ -420,7 +822,7 @@ async def get_synonym_map_names(self, **kwargs: Any) -> List[str]: :raises ~azure.core.exceptions.HttpResponseError: """ result = await self.get_synonym_maps(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @distributed_trace def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: @@ -430,7 +832,7 @@ def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: :rtype: ~azure.core.async_paging.AsyncItemPaged[str] :raises ~azure.core.exceptions.HttpResponseError: If the operation fails. """ - names = self.list_aliases(cls=lambda objs: [x.get("name") for x in objs], **kwargs) + names = self.list_aliases(cls=lambda objs: [x.name for x in objs], **kwargs) return cast(AsyncItemPaged[str], names) @@ -508,6 +910,91 @@ async def delete_data_source_connection( else: return await super().delete_data_source_connection(*args, **kwargs) + @overload + async def create_or_update_data_source_connection( + self, + data_source_name: str, + data_source: _models.SearchIndexerDataSourceConnection, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source_name: The name of the data source connection. Required. + :type data_source_name: str + :param data_source: The definition of the data source connection to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_data_source_connection( + self, + data_source: _models.SearchIndexerDataSourceConnection, + /, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source: The SearchIndexerDataSourceConnection object to create or update. Required. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_data_source_connection( + self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any + ) -> _models.SearchIndexerDataSourceConnection: + """Creates a new data source connection or updates a data source connection if it already exists. + + :param data_source_name: The name of the data source connection. Required. + :type data_source_name: str + :param data_source: The SearchIndexerDataSourceConnection object to create or update. + :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerDataSourceConnection + :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): + data_source = args[0] + kwargs.setdefault("etag", data_source.e_tag) + return await self._create_or_update_data_source_connection(data_source.name, data_source, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_data_source_connection(*args, prefer="return=representation", **kwargs) + @overload async def delete_indexer( self, @@ -577,6 +1064,100 @@ async def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwarg else: return await super().delete_indexer(*args, **kwargs) + @overload + async def create_or_update_indexer( + self, + indexer_name: str, + indexer: _models.SearchIndexer, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The definition of the indexer to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_indexer( + self, + indexer: _models.SearchIndexer, + /, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer: The SearchIndexer object to create or update. Required. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> _models.SearchIndexer: + """Creates a new indexer or updates an indexer if it already exists. + + :param indexer_name: The name of the indexer. Required. + :type indexer_name: str + :param indexer: The SearchIndexer object to create or update. + :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexer + :rtype: ~azure.search.documents.indexes.models.SearchIndexer + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexer): + indexer = args[0] + kwargs.setdefault("etag", indexer.e_tag) + return await self._create_or_update_indexer(indexer.name, indexer, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_indexer(*args, prefer="return=representation", **kwargs) + @overload async def delete_skillset( self, @@ -646,6 +1227,103 @@ async def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset] else: return await super().delete_skillset(*args, **kwargs) + @overload + async def create_or_update_skillset( + self, + skillset_name: str, + skillset: _models.SearchIndexerSkillset, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + etag: str | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The skillset containing one or more skills to create or update in a search + service. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @overload + async def create_or_update_skillset( + self, + skillset: _models.SearchIndexerSkillset, + /, + *, + skip_indexer_reset_requirement_for_cache: bool | None = None, + disable_cache_reprocessing_change_detection: bool | None = None, + match_condition: MatchConditions | None = None, + **kwargs: Any, + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset: The SearchIndexerSkillset object to create or update. Required. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + ... + + @distributed_trace_async + async def create_or_update_skillset( + self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any + ) -> _models.SearchIndexerSkillset: + """Creates a new skillset in a search service or updates the skillset if it already exists. + + :param skillset_name: The name of the skillset. Required. + :type skillset_name: str + :param skillset: The SearchIndexerSkillset object to create or update. + :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default + value is None. + :paramtype skip_indexer_reset_requirement_for_cache: bool + :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change + detection. Default value is None. + :paramtype disable_cache_reprocessing_change_detection: bool + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: SearchIndexerSkillset + :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset + :raises ~azure.core.exceptions.HttpResponseError: + """ + if args and isinstance(args[0], _models.SearchIndexerSkillset): + skillset = args[0] + kwargs.setdefault("etag", skillset.e_tag) + return await self._create_or_update_skillset(skillset.name, skillset, prefer="return=representation", **kwargs) + else: + return await self._create_or_update_skillset(*args, prefer="return=representation", **kwargs) + @overload async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: """Lists all skillsets available for a search service. @@ -725,7 +1403,7 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: :rtype: list[str] """ result = await self.get_indexers(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @overload async def get_data_source_connections( @@ -778,7 +1456,7 @@ async def get_data_source_connection_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_data_source_connections(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] @distributed_trace_async async def get_skillset_names(self, **kwargs) -> Sequence[str]: @@ -790,7 +1468,7 @@ async def get_skillset_names(self, **kwargs) -> Sequence[str]: """ result = await self.get_skillsets(**kwargs) - return [x.get("name") for x in result] + return [x.name for x in result] __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py index e7e31c666197..be962eb3ba27 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py @@ -136,14 +136,13 @@ async def _test_get_search_facets_result(self, client): async def _test_autocomplete(self, client): results = await client.autocomplete(search_text="mot", suggester_name="sg") - assert results == [{"text": "motel", "query_plus_text": "motel"}] + assert any(d.get('text') == 'motel' for d in results) + assert any(d.get('query_plus_text') == 'motel' for d in results) async def _test_suggest(self, client): results = await client.suggest(search_text="mot", suggester_name="sg") - assert results == [ - {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, - {"hotelId": "9", "text": "Secret Point Motel"}, - ] + assert {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."} in results + assert {"hotelId": "9", "text": "Secret Point Motel"} in results @SearchEnvVarPreparer() @search_decorator(schema="hotel_schema.json", index_batch="hotel_large.json") diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py index 8afea2e16425..00f99e9a47c0 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py @@ -44,8 +44,8 @@ async def test_search_index_client(self, endpoint, index_name): async def _test_get_service_statistics(self, client): result = await client.get_service_statistics() - assert isinstance(result, dict) - assert set(result.keys()) == {"counters", "limits"} + assert "counters" in set(result.keys()) + assert "limits" in set(result.keys()) async def _test_list_indexes_empty(self, client): result = client.list_indexes() diff --git a/sdk/search/azure-search-documents/tests/search_service_preparer.py b/sdk/search/azure-search-documents/tests/search_service_preparer.py index d4de15e3b660..ae0c44b01198 100644 --- a/sdk/search/azure-search-documents/tests/search_service_preparer.py +++ b/sdk/search/azure-search-documents/tests/search_service_preparer.py @@ -84,7 +84,7 @@ def _clean_up_indexers(endpoint, cred): def _set_up_index(service_name, endpoint, cred, schema, index_batch): from azure.search.documents import SearchClient from azure.search.documents.indexes.models import SearchIndex - from azure.search.documents._generated.models import IndexBatch + from azure.search.documents.models import IndexDocumentsBatch from azure.search.documents.indexes import SearchIndexClient schema = _load_schema(schema) @@ -92,13 +92,13 @@ def _set_up_index(service_name, endpoint, cred, schema, index_batch): if schema: index_json = json.loads(schema) index_name = index_json["name"] - index = SearchIndex.from_dict(index_json) + index = SearchIndex(index_json) index_client = SearchIndexClient(endpoint, cred, retry_backoff_factor=60) index_create = index_client.create_index(index) # optionally load data into the index if index_batch and schema: - batch = IndexBatch.deserialize(index_batch) + batch = IndexDocumentsBatch(index_batch) client = SearchClient(endpoint, index_name, cred) results = client.index_documents(batch) if not all(result.succeeded for result in results): diff --git a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py index af86da2542c6..e52e8c806da0 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py @@ -124,11 +124,10 @@ def _test_get_search_facets_result(self, client): def _test_autocomplete(self, client): results = client.autocomplete(search_text="mot", suggester_name="sg") - assert results == [{"text": "motel", "query_plus_text": "motel"}] + assert any(d.get('text') == 'motel' for d in results) + assert any(d.get('query_plus_text') == 'motel' for d in results) def _test_suggest(self, client): results = client.suggest(search_text="mot", suggester_name="sg") - assert results == [ - {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, - {"hotelId": "9", "text": "Secret Point Motel"}, - ] + assert {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."} in results + assert {"hotelId": "9", "text": "Secret Point Motel"} in results diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py index 149e4d46944c..0644e0be8423 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py @@ -41,8 +41,8 @@ def test_search_index_client(self, endpoint, index_name): def _test_get_service_statistics(self, client): result = client.get_service_statistics() - assert isinstance(result, dict) - assert set(result.keys()) == {"counters", "limits"} + assert "counters" in set(result.keys()) + assert "limits" in set(result.keys()) def _test_list_indexes_empty(self, client): result = client.list_indexes() diff --git a/sdk/search/azure-search-documents/tests/test_serialization.py b/sdk/search/azure-search-documents/tests/test_serialization.py index 09a5f04caf32..f7f524be26f0 100644 --- a/sdk/search/azure-search-documents/tests/test_serialization.py +++ b/sdk/search/azure-search-documents/tests/test_serialization.py @@ -45,8 +45,8 @@ def test_serialize_search_index(): index = SearchIndex( name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options ) - search_index_serialized = index.serialize() - search_index = SearchIndex.deserialize(search_index_serialized) + search_index_serialized = index.as_dict() + search_index = SearchIndex(search_index_serialized) assert search_index @@ -74,8 +74,8 @@ def test_serialize_search_indexer_skillset(): name="Skillset", skills=skills, cognitive_services_account=cognitive_services_account ) - serialized_skillset = skillset.serialize() - skillset = SearchIndexerSkillset.deserialize(serialized_skillset) + serialized_skillset = skillset.as_dict() + skillset = SearchIndexerSkillset(serialized_skillset) assert skillset @@ -104,5 +104,5 @@ def test_serialize_search_index_dict(): name=new_index_name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options ) search_index_serialized_dict = index.as_dict() - search_index = SearchIndex.from_dict(search_index_serialized_dict) + search_index = SearchIndex(search_index_serialized_dict) assert search_index From 21275e2ac257d63926368e5a1512d724cce60dfa Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Tue, 28 Oct 2025 18:01:35 -0700 Subject: [PATCH 28/40] update --- .../documents/indexes/_operations/_patch.py | 575 +++--------------- .../indexes/aio/_operations/_patch.py | 570 +++-------------- 2 files changed, 153 insertions(+), 992 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 4e7b799a7ae9..33751c2d1769 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -92,34 +93,7 @@ def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: An else: return super().delete_synonym_map(*args, **kwargs) - @overload - def create_or_update_synonym_map( - self, - synonym_map_name: str, - synonym_map: _models.SynonymMap, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def create_or_update_synonym_map( self, synonym_map: _models.SynonymMap, @@ -128,41 +102,13 @@ def create_or_update_synonym_map( match_condition: MatchConditions | None = None, **kwargs: Any, ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map: The SynonymMap object to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace - def create_or_update_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: Any) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The SynonymMap object to create or update. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SynonymMap): - synonym_map = args[0] - kwargs.setdefault("etag", synonym_map.e_tag) - return self._create_or_update_synonym_map(synonym_map.name, synonym_map, prefer="return=representation", **kwargs) - else: - return self._create_or_update_synonym_map(*args, prefer="return=representation", **kwargs) + return self._create_or_update_synonym_map( + name=synonym_map.name, + synonym_map=synonym_map, + prefer="return=representation", + etag=synonym_map.e_tag, + match_condition=match_condition, + **kwargs) @overload def delete_index( @@ -247,53 +193,13 @@ def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> else: return super().delete_index(*args, **kwargs) - @overload + @distributed_trace def create_or_update_index( self, - index_name: str, index: _models.SearchIndex, - *, allow_index_downtime: bool | None = None, - query_source_authorization: str | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload - def create_or_update_index( - self, - index: _models.SearchIndex, /, *, - allow_index_downtime: bool | None = None, - query_source_authorization: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any, ) -> _models.SearchIndex: @@ -317,70 +223,17 @@ def create_or_update_index( :rtype: ~azure.search.documents.indexes.models.SearchIndex :raises ~azure.core.exceptions.HttpResponseError: """ - ... + return self._create_or_update_index( + index_name=index.name, + index=index, + prefer="return=representation", + allow_index_downtime=allow_index_downtime, + etag=index.e_tag, + match_condition=match_condition, + **kwargs + ) @distributed_trace - def create_or_update_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The SearchIndex object to create or update. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndex): - index = args[0] - kwargs.setdefault("etag", index.e_tag) - return self._create_or_update_index(index.name, index, prefer="return=representation", **kwargs) - else: - return self._create_or_update_index(*args, prefer="return=representation", **kwargs) - - @overload - def create_or_update_alias( - self, - alias_name: str, - alias: _models.SearchAlias, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload def create_or_update_alias( self, alias: _models.SearchAlias, @@ -399,31 +252,14 @@ def create_or_update_alias( :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def create_or_update_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The SearchAlias object to create or update. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchAlias): - alias = args[0] - kwargs.setdefault("etag", alias.e_tag) - return self._create_or_update_alias(alias.name, alias, prefer="return=representation", **kwargs) - else: - return self._create_or_update_alias(*args, prefer="return=representation", **kwargs) + return self._create_or_update_alias( + alias_name=alias.name, + alias=alias, + prefer="return=representation", + etag=alias.e_tag, + match_condition=match_condition, + **kwargs + ) @overload def delete_alias( @@ -563,34 +399,7 @@ def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any) else: return super().delete_agent(*args, **kwargs) - @overload - def create_or_update_agent( - self, - agent_name: str, - agent: _models.KnowledgeAgent, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent: The definition of the agent to create or update. Required. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def create_or_update_agent( self, agent: _models.KnowledgeAgent, @@ -609,62 +418,16 @@ def create_or_update_agent( :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ - ... + return self._create_or_update_agent( + agent_name=agent.name, + agent=agent, + prefer="return=representation", + etag=agent.e_tag, + match_condition=match_condition, + **kwargs + ) @distributed_trace - def create_or_update_agent( - self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent: The KnowledgeAgent object to create or update. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.KnowledgeAgent): - agent = args[0] - kwargs.setdefault("etag", agent.e_tag) - return self._create_or_update_agent(agent.name, agent, prefer="return=representation", **kwargs) - else: - return self._create_or_update_agent(*args, prefer="return=representation", **kwargs) - - @overload - def create_or_update_knowledge_source( - self, - source_name: str, - knowledge_source: _models.KnowledgeSource, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates a knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload def create_or_update_knowledge_source( self, knowledge_source: _models.KnowledgeSource, @@ -683,33 +446,14 @@ def create_or_update_knowledge_source( :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def create_or_update_knowledge_source( - self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates a knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The KnowledgeSource object to create or update. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.KnowledgeSource): - knowledge_source = args[0] - kwargs.setdefault("etag", knowledge_source.e_tag) - return self._create_or_update_knowledge_source(knowledge_source.name, knowledge_source, prefer="return=representation", **kwargs) - else: - return self._create_or_update_knowledge_source(*args, prefer="return=representation", **kwargs) + return self._create_or_update_knowledge_source( + knowledge_source_name=knowledge_source.name, + knowledge_source=knowledge_source, + prefer="return=representation", + match_condition=match_condition, + etag=knowledge_source.e_tag, + **kwargs + ) @overload def delete_knowledge_source( @@ -906,38 +650,7 @@ def delete_data_source_connection( else: return super().delete_data_source_connection(*args, **kwargs) - @overload - def create_or_update_data_source_connection( - self, - data_source_name: str, - data_source: _models.SearchIndexerDataSourceConnection, - *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_name: The name of the data source connection. Required. - :type data_source_name: str - :param data_source: The definition of the data source connection to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def create_or_update_data_source_connection( self, data_source: _models.SearchIndexerDataSourceConnection, @@ -960,36 +673,15 @@ def create_or_update_data_source_connection( :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def create_or_update_data_source_connection( - self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any - ) -> _models.SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_name: The name of the data source connection. Required. - :type data_source_name: str - :param data_source: The SearchIndexerDataSourceConnection object to create or update. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): - data_source = args[0] - kwargs.setdefault("etag", data_source.e_tag) - return self._create_or_update_data_source_connection(data_source.name, data_source, prefer="return=representation", **kwargs) - else: - return self._create_or_update_data_source_connection(*args, prefer="return=representation", **kwargs) + return self._create_or_update_data_source_connection( + data_source_name=data_source.name, + data_source=data_source, + prefer="return=representation", + etag=data_source.e_tag, + match_condition=match_condition, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + **kwargs + ) @overload def delete_indexer( @@ -1060,42 +752,7 @@ def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any else: return super().delete_indexer(*args, **kwargs) - @overload - def create_or_update_indexer( - self, - indexer_name: str, - indexer: _models.SearchIndexer, - *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def create_or_update_indexer( self, indexer: _models.SearchIndexer, @@ -1122,37 +779,16 @@ def create_or_update_indexer( :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def create_or_update_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The SearchIndexer object to create or update. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexer): - indexer = args[0] - kwargs.setdefault("etag", indexer.e_tag) - return self._create_or_update_indexer(indexer.name, indexer, prefer="return=representation", **kwargs) - else: - return self._create_or_update_indexer(*args, prefer="return=representation", **kwargs) + return self._create_or_update_indexer( + indexer_name=indexer.name, + indexer=indexer, + prefer="return=representation", + etag=indexer.e_tag, + match_condition=match_condition, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs + ) @overload def delete_skillset( @@ -1223,43 +859,7 @@ def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kw else: return super().delete_skillset(*args, **kwargs) - @overload - def create_or_update_skillset( - self, - skillset_name: str, - skillset: _models.SearchIndexerSkillset, - *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def create_or_update_skillset( self, skillset: _models.SearchIndexerSkillset, @@ -1286,39 +886,16 @@ def create_or_update_skillset( :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def create_or_update_skillset( - self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The SearchIndexerSkillset object to create or update. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexerSkillset): - skillset = args[0] - kwargs.setdefault("etag", skillset.e_tag) - return self._create_or_update_skillset(skillset.name, skillset, prefer="return=representation", **kwargs) - else: - return self._create_or_update_skillset(*args, prefer="return=representation", **kwargs) + return self._create_or_update_skillset( + skillset_name=skillset.name, + skillset=skillset, + prefer="return=representation", + etag=skillset.e_tag, + match_condition=match_condition, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs + ) @overload def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index fe048dfcb575..3676da704626 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -93,34 +94,7 @@ async def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwar else: return await super().delete_synonym_map(*args, **kwargs) - @overload - async def create_or_update_synonym_map( - self, - synonym_map_name: str, - synonym_map: _models.SynonymMap, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The definition of the synonym map to create or update. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def create_or_update_synonym_map( self, synonym_map: _models.SynonymMap, @@ -139,33 +113,14 @@ async def create_or_update_synonym_map( :rtype: ~azure.search.documents.indexes.models.SynonymMap :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def create_or_update_synonym_map( - self, *args: Union[str, _models.SynonymMap], **kwargs: Any - ) -> _models.SynonymMap: - """Creates a new synonym map or updates a synonym map if it already exists. - - :param synonym_map_name: The name of the synonym map. Required. - :type synonym_map_name: str - :param synonym_map: The SynonymMap object to create or update. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SynonymMap - :rtype: ~azure.search.documents.indexes.models.SynonymMap - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SynonymMap): - synonym_map = args[0] - kwargs.setdefault("etag", synonym_map.e_tag) - return await self._create_or_update_synonym_map(synonym_map.name, synonym_map, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_synonym_map(*args, prefer="return=representation", **kwargs) + return await self._create_or_update_synonym_map( + synonym_map_name=synonym_map.name, + synonym_map=synonym_map, + prefer="return=representation", + match_condition=match_condition, + etag=synonym_map.e_tag, + **kwargs + ) @overload async def delete_index( @@ -250,53 +205,13 @@ async def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: A else: return await super().delete_index(*args, **kwargs) - @overload + @distributed_trace_async async def create_or_update_index( self, - index_name: str, index: _models.SearchIndex, - *, allow_index_downtime: bool | None = None, - query_source_authorization: str | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The definition of the index to create or update. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload - async def create_or_update_index( - self, - index: _models.SearchIndex, /, *, - allow_index_downtime: bool | None = None, - query_source_authorization: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any, ) -> _models.SearchIndex: @@ -320,72 +235,17 @@ async def create_or_update_index( :rtype: ~azure.search.documents.indexes.models.SearchIndex :raises ~azure.core.exceptions.HttpResponseError: """ - ... + return await self._create_or_update_index( + index_name=index.name, + index=index, + prefer="return=representation", + allow_index_downtime=allow_index_downtime, + match_condition=match_condition, + etag=index.e_tag, + **kwargs + ) @distributed_trace_async - async def create_or_update_index( - self, *args: Union[str, _models.SearchIndex], **kwargs: Any - ) -> _models.SearchIndex: - """Creates a new search index or updates an index if it already exists. - - :param index_name: The name of the index. Required. - :type index_name: str - :param index: The SearchIndex object to create or update. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters - to be added to an index by taking the index offline for at least a few seconds. This - temporarily causes indexing and query requests to fail. Performance and write availability of - the index can be impaired for several minutes after the index is updated, or longer for very - large indexes. Default value is None. - :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndex - :rtype: ~azure.search.documents.indexes.models.SearchIndex - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndex): - index = args[0] - kwargs.setdefault("etag", index.e_tag) - return await self._create_or_update_index(index.name, index, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_index(*args, prefer="return=representation", **kwargs) - - @overload - async def create_or_update_alias( - self, - alias_name: str, - alias: _models.SearchAlias, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The definition of the alias to create or update. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload async def create_or_update_alias( self, alias: _models.SearchAlias, @@ -404,31 +264,14 @@ async def create_or_update_alias( :rtype: ~azure.search.documents.indexes.models.SearchAlias :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def create_or_update_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> _models.SearchAlias: - """Creates a new search alias or updates an alias if it already exists. - - :param alias_name: The name of the alias. Required. - :type alias_name: str - :param alias: The SearchAlias object to create or update. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchAlias - :rtype: ~azure.search.documents.indexes.models.SearchAlias - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchAlias): - alias = args[0] - kwargs.setdefault("etag", alias.e_tag) - return await self._create_or_update_alias(alias.name, alias, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_alias(*args, prefer="return=representation", **kwargs) + return await self._create_or_update_alias( + alias_name=alias.name, + alias=alias, + prefer="return=representation", + match_condition=match_condition, + etag=alias.e_tag, + **kwargs + ) @overload async def delete_alias( @@ -568,34 +411,7 @@ async def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs else: return await super().delete_agent(*args, **kwargs) - @overload - async def create_or_update_agent( - self, - agent_name: str, - agent: _models.KnowledgeAgent, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent: The definition of the agent to create or update. Required. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def create_or_update_agent( self, agent: _models.KnowledgeAgent, @@ -614,62 +430,16 @@ async def create_or_update_agent( :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent :raises ~azure.core.exceptions.HttpResponseError: """ - ... + return await self._create_or_update_agent( + agent_name=agent.name, + agent=agent, + prefer="return=representation", + match_condition=match_condition, + etag=agent.e_tag, + **kwargs + ) @distributed_trace_async - async def create_or_update_agent( - self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent: The KnowledgeAgent object to create or update. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.KnowledgeAgent): - agent = args[0] - kwargs.setdefault("etag", agent.e_tag) - return await self._create_or_update_agent(agent.name, agent, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_agent(*args, prefer="return=representation", **kwargs) - - @overload - async def create_or_update_knowledge_source( - self, - source_name: str, - knowledge_source: _models.KnowledgeSource, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates a knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The definition of the knowledge source to create or update. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload async def create_or_update_knowledge_source( self, knowledge_source: _models.KnowledgeSource, @@ -688,33 +458,14 @@ async def create_or_update_knowledge_source( :rtype: ~azure.search.documents.indexes.models.KnowledgeSource :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def create_or_update_knowledge_source( - self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any - ) -> _models.KnowledgeSource: - """Creates a new knowledge source or updates a knowledge source if it already exists. - - :param source_name: The name of the knowledge source. Required. - :type source_name: str - :param knowledge_source: The KnowledgeSource object to create or update. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeSource - :rtype: ~azure.search.documents.indexes.models.KnowledgeSource - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.KnowledgeSource): - knowledge_source = args[0] - kwargs.setdefault("etag", knowledge_source.e_tag) - return await self._create_or_update_knowledge_source(knowledge_source.name, knowledge_source, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_knowledge_source(*args, prefer="return=representation", **kwargs) + return await self._create_or_update_knowledge_source( + knowledge_source_name=knowledge_source.name, + knowledge_source=knowledge_source, + prefer="return=representation", + match_condition=match_condition, + etag=knowledge_source.e_tag, + **kwargs + ) @overload async def delete_knowledge_source( @@ -910,38 +661,7 @@ async def delete_data_source_connection( else: return await super().delete_data_source_connection(*args, **kwargs) - @overload - async def create_or_update_data_source_connection( - self, - data_source_name: str, - data_source: _models.SearchIndexerDataSourceConnection, - *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_name: The name of the data source connection. Required. - :type data_source_name: str - :param data_source: The definition of the data source connection to create or update. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def create_or_update_data_source_connection( self, data_source: _models.SearchIndexerDataSourceConnection, @@ -964,36 +684,15 @@ async def create_or_update_data_source_connection( :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def create_or_update_data_source_connection( - self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any - ) -> _models.SearchIndexerDataSourceConnection: - """Creates a new data source connection or updates a data source connection if it already exists. - - :param data_source_name: The name of the data source connection. Required. - :type data_source_name: str - :param data_source: The SearchIndexerDataSourceConnection object to create or update. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerDataSourceConnection - :rtype: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): - data_source = args[0] - kwargs.setdefault("etag", data_source.e_tag) - return await self._create_or_update_data_source_connection(data_source.name, data_source, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_data_source_connection(*args, prefer="return=representation", **kwargs) + return await self._create_or_update_data_source_connection( + data_source_name=data_source.name, + data_source=data_source, + prefer="return=representation", + match_condition=match_condition, + etag=data_source.e_tag, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + **kwargs + ) @overload async def delete_indexer( @@ -1064,42 +763,7 @@ async def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwarg else: return await super().delete_indexer(*args, **kwargs) - @overload - async def create_or_update_indexer( - self, - indexer_name: str, - indexer: _models.SearchIndexer, - *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The definition of the indexer to create or update. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def create_or_update_indexer( self, indexer: _models.SearchIndexer, @@ -1126,37 +790,16 @@ async def create_or_update_indexer( :rtype: ~azure.search.documents.indexes.models.SearchIndexer :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def create_or_update_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> _models.SearchIndexer: - """Creates a new indexer or updates an indexer if it already exists. - - :param indexer_name: The name of the indexer. Required. - :type indexer_name: str - :param indexer: The SearchIndexer object to create or update. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexer - :rtype: ~azure.search.documents.indexes.models.SearchIndexer - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexer): - indexer = args[0] - kwargs.setdefault("etag", indexer.e_tag) - return await self._create_or_update_indexer(indexer.name, indexer, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_indexer(*args, prefer="return=representation", **kwargs) + return await self._create_or_update_indexer( + indexer_name=indexer.name, + indexer=indexer, + prefer="return=representation", + match_condition=match_condition, + etag=indexer.e_tag, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs + ) @overload async def delete_skillset( @@ -1227,43 +870,7 @@ async def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset] else: return await super().delete_skillset(*args, **kwargs) - @overload - async def create_or_update_skillset( - self, - skillset_name: str, - skillset: _models.SearchIndexerSkillset, - *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The skillset containing one or more skills to create or update in a search - service. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def create_or_update_skillset( self, skillset: _models.SearchIndexerSkillset, @@ -1290,39 +897,16 @@ async def create_or_update_skillset( :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def create_or_update_skillset( - self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any - ) -> _models.SearchIndexerSkillset: - """Creates a new skillset in a search service or updates the skillset if it already exists. - - :param skillset_name: The name of the skillset. Required. - :type skillset_name: str - :param skillset: The SearchIndexerSkillset object to create or update. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword skip_indexer_reset_requirement_for_cache: Ignores cache reset requirements. Default - value is None. - :paramtype skip_indexer_reset_requirement_for_cache: bool - :keyword disable_cache_reprocessing_change_detection: Disables cache reprocessing change - detection. Default value is None. - :paramtype disable_cache_reprocessing_change_detection: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: SearchIndexerSkillset - :rtype: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexerSkillset): - skillset = args[0] - kwargs.setdefault("etag", skillset.e_tag) - return await self._create_or_update_skillset(skillset.name, skillset, prefer="return=representation", **kwargs) - else: - return await self._create_or_update_skillset(*args, prefer="return=representation", **kwargs) + return await self._create_or_update_skillset( + skillset_name=skillset.name, + skillset=skillset, + prefer="return=representation", + match_condition=match_condition, + etag=skillset.e_tag, + skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, + disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, + **kwargs + ) @overload async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: From 376ce8c4307d5a7df6205a6ef28d546e232d2d9f Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 29 Oct 2025 10:32:14 -0700 Subject: [PATCH 29/40] update --- .../azure/search/documents/_operations/_patch.py | 8 ++++---- .../azure/search/documents/aio/_operations/_patch.py | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 36e9477b51fd..564cf7ecacb2 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -381,7 +381,7 @@ def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models :dedent: 4 :caption: Upload new documents to an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_upload_actions(documents) result = self.index_documents(batch, **kwargs) @@ -409,7 +409,7 @@ def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models :dedent: 4 :caption: Delete documents from an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_delete_actions(documents) result = self.index_documents(batch, **kwargs) @@ -437,7 +437,7 @@ def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models. :dedent: 4 :caption: Merge documents in an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_merge_actions(documents) result = self.index_documents(batch, **kwargs) @@ -464,7 +464,7 @@ def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> Lis :dedent: 4 :caption: Merge or upload documents to an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_merge_or_upload_actions(documents) result = self.index_documents(batch, **kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 3e1f3b4da393..b1cf4c3b3ce3 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -215,7 +215,7 @@ async def _index_documents_actions( result_first_half = batch_response_first_half else: result_first_half = [] - batch_response_second_half = await self._index_documents_actions(actions=actions[pos:], **kwargs) + batch_response_second_half = await self._index_documents_actions(actions=batch.actions[pos:], **kwargs) if batch_response_second_half: result_second_half = batch_response_second_half else: @@ -244,7 +244,7 @@ async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ :dedent: 4 :caption: Upload new documents to an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_upload_actions(documents) result = await self.index_documents(batch, **kwargs) @@ -272,7 +272,7 @@ async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ :dedent: 4 :caption: Delete documents from an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_delete_actions(documents) result = await self.index_documents(batch, **kwargs) @@ -300,7 +300,7 @@ async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_m :dedent: 4 :caption: Merge documents in an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_merge_actions(documents) result = await self.index_documents(batch, **kwargs) @@ -327,7 +327,7 @@ async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) :dedent: 4 :caption: Merge or upload documents to an index """ - batch = _models.IndexDocumentsBatch() + batch = _models.IndexDocumentsBatch(actions=[]) batch.add_merge_or_upload_actions(documents) result = await self.index_documents(batch, **kwargs) From 161b9e1f1e5e82e06f9df1be8b83450d53ec9ede Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 29 Oct 2025 12:02:44 -0700 Subject: [PATCH 30/40] update --- .../search/documents/_operations/_patch.py | 4 +- .../azure/search/documents/_patch.py | 6 +- .../documents/aio/_operations/_patch.py | 4 +- .../azure/search/documents/aio/_patch.py | 19 +- .../indexes/_operations/_operations.py | 16 +- .../documents/indexes/_operations/_patch.py | 691 +++++------------- .../indexes/aio/_operations/_operations.py | 16 +- .../indexes/aio/_operations/_patch.py | 690 +++++------------ .../search/documents/indexes/models/_patch.py | 2 +- .../azure/search/documents/models/__init__.py | 2 + .../azure/search/documents/models/_models.py | 6 +- 11 files changed, 390 insertions(+), 1066 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 564cf7ecacb2..942b8000a957 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -808,7 +808,7 @@ def autocomplete( search_fields: Optional[str] = None, top: Optional[int] = None, **kwargs: Any, - ) -> List[Dict[str, Any]]: + ) -> List[_models.AutocompleteItem]: """Autocomplete incomplete search terms based on input text and matching terms in the index. :param str search_text: The search text on which to base autocomplete results. @@ -884,7 +884,7 @@ def suggest( select: Optional[str] = None, top: Optional[int] = None, **kwargs: Any, - ) -> List[Dict[str, Any]]: + ) -> List[_models.SuggestResult]: """Get search suggestions for documents in the Azure search index. :param str search_text: The search text to use to suggest documents. Must be at least 1 diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index d4fcc286556c..7c7fa989a77f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -7,8 +7,10 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Union from enum import Enum from azure.core import CaseInsensitiveEnumMeta +from azure.core.credentials import AzureKeyCredential, TokenCredential from ._client import SearchClient as _SearchClient from ._operations._patch import SearchItemPaged from .models._patch import RequestEntityTooLargeError @@ -27,7 +29,9 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): class SearchClient(_SearchClient): """SearchClient customizations go here.""" - def __init__(self, endpoint, index_name, credential, **kwargs): + def __init__( + self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any + ): super().__init__(endpoint, credential, index_name, **kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index b1cf4c3b3ce3..e518b79755ac 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -602,7 +602,7 @@ async def autocomplete( search_fields: Optional[str] = None, top: Optional[int] = None, **kwargs: Any, - ) -> List[Dict[str, Any]]: + ) -> List[_models.AutocompleteItem]: """Autocomplete incomplete search terms based on input text and matching terms in the index. :param str search_text: The search text on which to base autocomplete results. @@ -678,7 +678,7 @@ async def suggest( select: Optional[str] = None, top: Optional[int] = None, **kwargs: Any, - ) -> List[Dict[str, Any]]: + ) -> List[_models.SuggestResult]: """Get search suggestions for documents in the Azure search index. :param str search_text: The search text to use to suggest documents. Must be at least 1 diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index 87676c65a8f0..5d9f50e649cb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -7,9 +7,26 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Union, TYPE_CHECKING +from azure.core.credentials import AzureKeyCredential +from azure.core.credentials_async import AsyncTokenCredential +from ._client import SearchClient as _SearchClient +from ._operations._patch import AsyncSearchItemPaged -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +class SearchClient(_SearchClient): + """SearchClient customizations go here.""" + + def __init__( + self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any + ): + super().__init__(endpoint, credential, index_name, **kwargs) + + +__all__: list[str] = [ + "SearchClient", + "AsyncSearchItemPaged", +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index 011d46b73c16..b73bfd6358ac 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -1580,7 +1580,7 @@ def _create_or_update_synonym_map( return deserialized # type: ignore @distributed_trace - def delete_synonym_map( # pylint: disable=inconsistent-return-statements + def _delete_synonym_map( # pylint: disable=inconsistent-return-statements self, synonym_map_name: str, *, @@ -2049,7 +2049,7 @@ def _create_or_update_index( return deserialized # type: ignore @distributed_trace - def delete_index( # pylint: disable=inconsistent-return-statements + def _delete_index( # pylint: disable=inconsistent-return-statements self, index_name: str, *, @@ -2771,7 +2771,7 @@ def _create_or_update_alias( return deserialized # type: ignore @distributed_trace - def delete_alias( # pylint: disable=inconsistent-return-statements + def _delete_alias( # pylint: disable=inconsistent-return-statements self, alias_name: str, *, @@ -3236,7 +3236,7 @@ def _create_or_update_agent( return deserialized # type: ignore @distributed_trace - def delete_agent( # pylint: disable=inconsistent-return-statements + def _delete_agent( # pylint: disable=inconsistent-return-statements self, agent_name: str, *, @@ -3704,7 +3704,7 @@ def _create_or_update_knowledge_source( return deserialized # type: ignore @distributed_trace - def delete_knowledge_source( # pylint: disable=inconsistent-return-statements + def _delete_knowledge_source( # pylint: disable=inconsistent-return-statements self, source_name: str, *, @@ -4336,7 +4336,7 @@ def _create_or_update_data_source_connection( return deserialized # type: ignore @distributed_trace - def delete_data_source_connection( # pylint: disable=inconsistent-return-statements + def _delete_data_source_connection( # pylint: disable=inconsistent-return-statements self, data_source_name: str, *, @@ -5148,7 +5148,7 @@ def _create_or_update_indexer( return deserialized # type: ignore @distributed_trace - def delete_indexer( # pylint: disable=inconsistent-return-statements + def _delete_indexer( # pylint: disable=inconsistent-return-statements self, indexer_name: str, *, @@ -5682,7 +5682,7 @@ def _create_or_update_skillset( return deserialized # type: ignore @distributed_trace - def delete_skillset( # pylint: disable=inconsistent-return-statements + def _delete_skillset( # pylint: disable=inconsistent-return-statements self, skillset_name: str, *, diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 33751c2d1769..1e1624c3a7e4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -8,7 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Iterator, cast, List, Sequence, Union, overload +from typing import Any, Iterator, cast, List, Sequence, Union from azure.core import MatchConditions from azure.core.paging import ItemPaged @@ -24,34 +24,10 @@ class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexClient.""" - @overload - def delete_synonym_map( - self, - synonym_map_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a synonym map. - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def delete_synonym_map( self, - synonym_map: _models.SynonymMap, + synonym_map: Union[str, _models.SynonymMap], /, *, match_condition: MatchConditions | None = None, @@ -59,39 +35,28 @@ def delete_synonym_map( ) -> None: """Deletes a synonym map. - :param synonym_map: The SynonymMap object to delete. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace - def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: Any) -> None: - """Deletes a synonym map. - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :param synonym_map: The SynonymMap object to delete. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param synonym_map: The name of the synonym map to delete or a SynonymMap object. Required. + :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.SynonymMap): - synonym_map = args[0] - kwargs.setdefault("etag", synonym_map.e_tag) - return super().delete_synonym_map(synonym_map.name, **kwargs) - else: - return super().delete_synonym_map(*args, **kwargs) + try: + name: str = synonym_map.name # type: ignore + return self._delete_synonym_map( + synonym_map_name=name, + match_condition=match_condition, + etag=synonym_map.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = synonym_map # type: ignore + return self._delete_synonym_map( + synonym_map_name=name, + **kwargs, + ) @distributed_trace def create_or_update_synonym_map( @@ -108,90 +73,42 @@ def create_or_update_synonym_map( prefer="return=representation", etag=synonym_map.e_tag, match_condition=match_condition, - **kwargs) - - @overload - def delete_index( - self, - index_name: str, - *, - query_source_authorization: str | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a search index and all the documents it contains. - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... + **kwargs, + ) - @overload + @distributed_trace def delete_index( self, - index: _models.SearchIndex, + index: Union[str, _models.SearchIndex], /, *, - query_source_authorization: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any, ) -> None: """Deletes a search index and all the documents it contains. - :param index: The SearchIndex object to delete. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str + :param index: The name of the index to delete or a SearchIndex object. Required. + :type index: str or ~azure.search.documents.indexes.models.SearchIndex :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> None: - """Deletes a search index and all the documents it contains. - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :param index: The SearchIndex object to delete. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndex): - index = args[0] - kwargs.setdefault("etag", index.e_tag) - return super().delete_index(index.name, **kwargs) - else: - return super().delete_index(*args, **kwargs) + try: + name: str = index.name # type: ignore + return self._delete_index( + index_name=name, + match_condition=match_condition, + etag=index.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = index # type: ignore + return self._delete_index( + index_name=name, + **kwargs, + ) @distributed_trace def create_or_update_index( @@ -213,10 +130,6 @@ def create_or_update_index( the index can be impaired for several minutes after the index is updated, or longer for very large indexes. Default value is None. :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: SearchIndex @@ -230,7 +143,7 @@ def create_or_update_index( allow_index_downtime=allow_index_downtime, etag=index.e_tag, match_condition=match_condition, - **kwargs + **kwargs, ) @distributed_trace @@ -258,37 +171,13 @@ def create_or_update_alias( prefer="return=representation", etag=alias.e_tag, match_condition=match_condition, - **kwargs + **kwargs, ) - @overload - def delete_alias( - self, - alias_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a search alias and its associated mapping to an index. - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def delete_alias( self, - alias: _models.SearchAlias, + alias: Union[str, _models.SearchAlias], /, *, match_condition: MatchConditions | None = None, @@ -296,68 +185,33 @@ def delete_alias( ) -> None: """Deletes a search alias and its associated mapping to an index. - :param alias: The SearchAlias object to delete. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias + :param alias: The name of the alias to delete or a SearchAlias object. Required. + :type alias: str or ~azure.search.documents.indexes.models.SearchAlias :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... + try: + name: str = alias.name # type: ignore + return self._delete_alias( + alias_name=name, + match_condition=match_condition, + etag=alias.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = alias # type: ignore + return self._delete_alias( + alias_name=name, + **kwargs, + ) @distributed_trace - def delete_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> None: - """Deletes a search alias and its associated mapping to an index. - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :param alias: The SearchAlias object to delete. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchAlias): - alias = args[0] - kwargs.setdefault("etag", alias.e_tag) - return super().delete_alias(alias.name, **kwargs) - else: - return super().delete_alias(*args, **kwargs) - - @overload - def delete_agent( - self, - agent_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a knowledge agent. - - :param agent_name: The name of the agent to delete. Required. - :type agent_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload def delete_agent( self, - agent: _models.KnowledgeAgent, + agent: Union[str, _models.KnowledgeAgent], /, *, match_condition: MatchConditions | None = None, @@ -365,39 +219,28 @@ def delete_agent( ) -> None: """Deletes a knowledge agent. - :param agent: The KnowledgeAgent object to delete. Required. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param agent: The name of the agent to delete or a KnowledgeAgent object. Required. + :type agent: str or ~azure.search.documents.indexes.models.KnowledgeAgent :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any) -> None: - """Deletes a knowledge agent. - - :param agent_name: The name of the agent to delete. Required. - :type agent_name: str - :param agent: The KnowledgeAgent object to delete. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.KnowledgeAgent): - agent = args[0] - kwargs.setdefault("etag", agent.e_tag) - return super().delete_agent(agent.name, **kwargs) - else: - return super().delete_agent(*args, **kwargs) + try: + name: str = agent.name # type: ignore + return self._delete_agent( + agent_name=name, + match_condition=match_condition, + etag=agent.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = agent # type: ignore + return self._delete_agent( + agent_name=name, + **kwargs, + ) @distributed_trace def create_or_update_agent( @@ -424,7 +267,7 @@ def create_or_update_agent( prefer="return=representation", etag=agent.e_tag, match_condition=match_condition, - **kwargs + **kwargs, ) @distributed_trace @@ -452,37 +295,13 @@ def create_or_update_knowledge_source( prefer="return=representation", match_condition=match_condition, etag=knowledge_source.e_tag, - **kwargs + **kwargs, ) - @overload - def delete_knowledge_source( - self, - source_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def delete_knowledge_source( self, - knowledge_source: _models.KnowledgeSource, + knowledge_source: Union[str, _models.KnowledgeSource], /, *, match_condition: MatchConditions | None = None, @@ -490,39 +309,28 @@ def delete_knowledge_source( ) -> None: """Deletes a knowledge source. - :param knowledge_source: The KnowledgeSource object to delete. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource + :param knowledge_source: The name of the knowledge source to delete or a KnowledgeSource object. Required. + :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def delete_knowledge_source(self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any) -> None: - """Deletes a knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :param knowledge_source: The KnowledgeSource object to delete. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.KnowledgeSource): - knowledge_source = args[0] - kwargs.setdefault("etag", knowledge_source.e_tag) - return super().delete_knowledge_source(knowledge_source.name, **kwargs) - else: - return super().delete_knowledge_source(*args, **kwargs) + try: + name: str = knowledge_source.name # type: ignore + return self._delete_knowledge_source( + source_name=name, + match_condition=match_condition, + etag=knowledge_source.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = knowledge_source # type: ignore + return self._delete_knowledge_source( + source_name=name, + **kwargs, + ) @distributed_trace def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: @@ -549,7 +357,8 @@ def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: """ result = self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy - typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + # typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + typed_result = result.synonym_maps return typed_result @distributed_trace @@ -579,34 +388,10 @@ def list_alias_names(self, **kwargs: Any) -> ItemPaged[str]: class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexerClient.""" - @overload - def delete_data_source_connection( - self, - data_source_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a data source connection. - - :param data_source_name: The name of the data source connection to delete. Required. - :type data_source_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def delete_data_source_connection( self, - data_source: _models.SearchIndexerDataSourceConnection, + data_source: Union[str, _models.SearchIndexerDataSourceConnection], /, *, match_condition: MatchConditions | None = None, @@ -614,41 +399,28 @@ def delete_data_source_connection( ) -> None: """Deletes a data source connection. - :param data_source: The SearchIndexerDataSourceConnection object to delete. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace - def delete_data_source_connection( - self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any - ) -> None: - """Deletes a data source connection. - - :param data_source_name: The name of the data source connection to delete. Required. - :type data_source_name: str - :param data_source: The SearchIndexerDataSourceConnection object to delete. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param data_source: The name of the data source connection to delete or a SearchIndexerDataSourceConnection object. Required. + :type data_source: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): - data_source = args[0] - kwargs.setdefault("etag", data_source.e_tag) - return super().delete_data_source_connection(data_source.name, **kwargs) - else: - return super().delete_data_source_connection(*args, **kwargs) + try: + name: str = data_source.name # type: ignore + return self._delete_data_source_connection( + data_source_name=name, + match_condition=match_condition, + etag=data_source.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = data_source # type: ignore + return self._delete_data_source_connection( + data_source_name=name, + **kwargs, + ) @distributed_trace def create_or_update_data_source_connection( @@ -680,37 +452,13 @@ def create_or_update_data_source_connection( etag=data_source.e_tag, match_condition=match_condition, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - **kwargs + **kwargs, ) - @overload - def delete_indexer( - self, - indexer_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes an indexer. - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def delete_indexer( self, - indexer: _models.SearchIndexer, + indexer: Union[str, _models.SearchIndexer], /, *, match_condition: MatchConditions | None = None, @@ -718,39 +466,28 @@ def delete_indexer( ) -> None: """Deletes an indexer. - :param indexer: The SearchIndexer object to delete. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :param indexer: The name of the indexer to delete or a SearchIndexer object. Required. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> None: - """Deletes an indexer. - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :param indexer: The SearchIndexer object to delete. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexer): - indexer = args[0] - kwargs.setdefault("etag", indexer.e_tag) - return super().delete_indexer(indexer.name, **kwargs) - else: - return super().delete_indexer(*args, **kwargs) + try: + name: str = indexer.name # type: ignore + return self._delete_indexer( + indexer_name=name, + match_condition=match_condition, + etag=indexer.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = indexer # type: ignore + return self._delete_indexer( + indexer_name=name, + **kwargs, + ) @distributed_trace def create_or_update_indexer( @@ -787,37 +524,13 @@ def create_or_update_indexer( match_condition=match_condition, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs + **kwargs, ) - @overload - def delete_skillset( - self, - skillset_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a skillset. - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace def delete_skillset( self, - skillset: _models.SearchIndexerSkillset, + skillset: Union[str, _models.SearchIndexerSkillset], /, *, match_condition: MatchConditions | None = None, @@ -825,39 +538,28 @@ def delete_skillset( ) -> None: """Deletes a skillset. - :param skillset: The SearchIndexerSkillset object to delete. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace - def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any) -> None: - """Deletes a skillset. - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :param skillset: The SearchIndexerSkillset object to delete. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param skillset: The name of the skillset to delete or a SearchIndexerSkillset object. Required. + :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.SearchIndexerSkillset): - skillset = args[0] - kwargs.setdefault("etag", skillset.e_tag) - return super().delete_skillset(skillset.name, **kwargs) - else: - return super().delete_skillset(*args, **kwargs) + try: + name: str = skillset.name # type: ignore + return self._delete_skillset( + skillset_name=name, + match_condition=match_condition, + etag=skillset.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = skillset # type: ignore + return self._delete_skillset( + skillset_name=name, + **kwargs, + ) @distributed_trace def create_or_update_skillset( @@ -894,25 +596,11 @@ def create_or_update_skillset( match_condition=match_condition, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs + **kwargs, ) - @overload - def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: - """Lists all skillsets available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: List of all the SearchIndexerSkillsets. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - @distributed_trace - def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: """Lists all skillsets available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -923,27 +611,16 @@ def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] :raises ~azure.core.exceptions.HttpResponseError: """ + if select is not None: + kwargs['select'] = ",".join(select) result = self._get_skillsets(**kwargs) assert result.skillsets is not None # Hint for mypy - typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + # typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + typed_result = result.skillsets return typed_result - @overload - def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: - """Lists all indexers available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: List of all the SearchIndexers. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - @distributed_trace - def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: + def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -953,19 +630,13 @@ def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: :return: List of all the SearchIndexers. :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_indexers_operations.py - :start-after: [START list_indexer] - :end-before: [END list_indexer] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers """ + if select is not None: + kwargs['select'] = ",".join(select) result = self._get_indexers(**kwargs) assert result.indexers is not None # Hint for mypy - typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + # typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + typed_result = result.indexers return typed_result @distributed_trace @@ -987,7 +658,7 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: result = self.get_indexers(**kwargs) return [x.name for x in result] - @overload + @distributed_trace def get_data_source_connections( self, *, select: str | None = None, **kwargs: Any ) -> List[_models.SearchIndexerDataSourceConnection]: @@ -1001,32 +672,12 @@ def get_data_source_connections( :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace - def get_data_source_connections(self, **kwargs: Any) -> List[_models.SearchIndexerDataSourceConnection]: - """Lists all data source connections available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: List of all the data source connections. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_data_source_operations.py - :start-after: [START list_data_source_connection] - :end-before: [END list_data_source_connection] - :language: python - :dedent: 4 - :caption: List all the data source connections - """ + if select is not None: + kwargs['select'] = ",".join(select) result = self._get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy - typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + # typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + typed_result = result.data_sources return typed_result @distributed_trace diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 8a221b3e6f8a..974305d5c5b6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -231,7 +231,7 @@ async def _create_or_update_synonym_map( return deserialized # type: ignore @distributed_trace_async - async def delete_synonym_map( + async def _delete_synonym_map( self, synonym_map_name: str, *, @@ -700,7 +700,7 @@ async def _create_or_update_index( return deserialized # type: ignore @distributed_trace_async - async def delete_index( + async def _delete_index( self, index_name: str, *, @@ -1425,7 +1425,7 @@ async def _create_or_update_alias( return deserialized # type: ignore @distributed_trace_async - async def delete_alias( + async def _delete_alias( self, alias_name: str, *, @@ -1893,7 +1893,7 @@ async def _create_or_update_agent( return deserialized # type: ignore @distributed_trace_async - async def delete_agent( + async def _delete_agent( self, agent_name: str, *, @@ -2362,7 +2362,7 @@ async def _create_or_update_knowledge_source( return deserialized # type: ignore @distributed_trace_async - async def delete_knowledge_source( + async def _delete_knowledge_source( self, source_name: str, *, @@ -2995,7 +2995,7 @@ async def _create_or_update_data_source_connection( return deserialized # type: ignore @distributed_trace_async - async def delete_data_source_connection( + async def _delete_data_source_connection( self, data_source_name: str, *, @@ -3807,7 +3807,7 @@ async def _create_or_update_indexer( return deserialized # type: ignore @distributed_trace_async - async def delete_indexer( + async def _delete_indexer( self, indexer_name: str, *, @@ -4343,7 +4343,7 @@ async def _create_or_update_skillset( return deserialized # type: ignore @distributed_trace_async - async def delete_skillset( + async def _delete_skillset( self, skillset_name: str, *, diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index 3676da704626..ad47b35466eb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -8,7 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, AsyncIterator, cast, List, Sequence, Union, overload +from typing import Any, AsyncIterator, cast, List, Sequence, Union from azure.core import MatchConditions from azure.core.async_paging import AsyncItemPaged @@ -25,34 +25,10 @@ class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexClient (async).""" - @overload - async def delete_synonym_map( - self, - synonym_map_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a synonym map. - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_synonym_map( self, - synonym_map: _models.SynonymMap, + synonym_map: Union[str, _models.SynonymMap], /, *, match_condition: MatchConditions | None = None, @@ -60,39 +36,28 @@ async def delete_synonym_map( ) -> None: """Deletes a synonym map. - :param synonym_map: The SynonymMap object to delete. Required. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap + :param synonym_map: The name of the synonym map to delete or a SynonymMap object. Required. + :type synonym_map: str or ~azure.search.documents.indexes.models.SynonymMap :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def delete_synonym_map(self, *args: Union[str, _models.SynonymMap], **kwargs: Any) -> None: - """Deletes a synonym map. - - :param synonym_map_name: The name of the synonym map to delete. Required. - :type synonym_map_name: str - :param synonym_map: The SynonymMap object to delete. - :type synonym_map: ~azure.search.documents.indexes.models.SynonymMap - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SynonymMap): - synonym_map = args[0] - kwargs.setdefault("etag", synonym_map.e_tag) - return await super().delete_synonym_map(synonym_map.name, **kwargs) - else: - return await super().delete_synonym_map(*args, **kwargs) + try: + name: str = synonym_map.name # type: ignore + return await self._delete_synonym_map( + synonym_map_name=name, + match_condition=match_condition, + etag=synonym_map.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = synonym_map # type: ignore + return await self._delete_synonym_map( + synonym_map_name=name, + **kwargs, + ) @distributed_trace_async async def create_or_update_synonym_map( @@ -119,91 +84,42 @@ async def create_or_update_synonym_map( prefer="return=representation", match_condition=match_condition, etag=synonym_map.e_tag, - **kwargs + **kwargs, ) - @overload - async def delete_index( - self, - index_name: str, - *, - query_source_authorization: str | None = None, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a search index and all the documents it contains. - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_index( self, - index: _models.SearchIndex, + index: Union[str, _models.SearchIndex], /, *, - query_source_authorization: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any, ) -> None: """Deletes a search index and all the documents it contains. - :param index: The SearchIndex object to delete. Required. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace_async - async def delete_index(self, *args: Union[str, _models.SearchIndex], **kwargs: Any) -> None: - """Deletes a search index and all the documents it contains. - - :param index_name: The name of the index to delete. Required. - :type index_name: str - :param index: The SearchIndex object to delete. - :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param index: The name of the index to delete or a SearchIndex object. Required. + :type index: str or ~azure.search.documents.indexes.models.SearchIndex :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.SearchIndex): - index = args[0] - kwargs.setdefault("etag", index.e_tag) - return await super().delete_index(index.name, **kwargs) - else: - return await super().delete_index(*args, **kwargs) + try: + name: str = index.name # type: ignore + return await self._delete_index( + index_name=name, + match_condition=match_condition, + etag=index.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = index # type: ignore + return await self._delete_index( + index_name=name, + **kwargs, + ) @distributed_trace_async async def create_or_update_index( @@ -225,10 +141,6 @@ async def create_or_update_index( the index can be impaired for several minutes after the index is updated, or longer for very large indexes. Default value is None. :paramtype allow_index_downtime: bool - :keyword query_source_authorization: Token identifying the user for which the query is being - executed. This token is used to enforce security restrictions on documents. Default value is - None. - :paramtype query_source_authorization: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: SearchIndex @@ -242,7 +154,7 @@ async def create_or_update_index( allow_index_downtime=allow_index_downtime, match_condition=match_condition, etag=index.e_tag, - **kwargs + **kwargs, ) @distributed_trace_async @@ -270,37 +182,13 @@ async def create_or_update_alias( prefer="return=representation", match_condition=match_condition, etag=alias.e_tag, - **kwargs + **kwargs, ) - @overload - async def delete_alias( - self, - alias_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a search alias and its associated mapping to an index. - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_alias( self, - alias: _models.SearchAlias, + alias: Union[str, _models.SearchAlias], /, *, match_condition: MatchConditions | None = None, @@ -308,68 +196,33 @@ async def delete_alias( ) -> None: """Deletes a search alias and its associated mapping to an index. - :param alias: The SearchAlias object to delete. Required. - :type alias: ~azure.search.documents.indexes.models.SearchAlias + :param alias: The name of the alias to delete or a SearchAlias object. Required. + :type alias: str or ~azure.search.documents.indexes.models.SearchAlias :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... + try: + name: str = alias.name # type: ignore + return await self._delete_alias( + alias_name=name, + match_condition=match_condition, + etag=alias.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = alias # type: ignore + return await self._delete_alias( + alias_name=name, + **kwargs, + ) @distributed_trace_async - async def delete_alias(self, *args: Union[str, _models.SearchAlias], **kwargs: Any) -> None: - """Deletes a search alias and its associated mapping to an index. - - :param alias_name: The name of the alias to delete. Required. - :type alias_name: str - :param alias: The SearchAlias object to delete. - :type alias: ~azure.search.documents.indexes.models.SearchAlias - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchAlias): - alias = args[0] - kwargs.setdefault("etag", alias.e_tag) - return await super().delete_alias(alias.name, **kwargs) - else: - return await super().delete_alias(*args, **kwargs) - - @overload - async def delete_agent( - self, - agent_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a knowledge agent. - - :param agent_name: The name of the agent to delete. Required. - :type agent_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload async def delete_agent( self, - agent: _models.KnowledgeAgent, + agent: Union[str, _models.KnowledgeAgent], /, *, match_condition: MatchConditions | None = None, @@ -377,39 +230,28 @@ async def delete_agent( ) -> None: """Deletes a knowledge agent. - :param agent: The KnowledgeAgent object to delete. Required. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace_async - async def delete_agent(self, *args: Union[str, _models.KnowledgeAgent], **kwargs: Any) -> None: - """Deletes a knowledge agent. - - :param agent_name: The name of the agent to delete. Required. - :type agent_name: str - :param agent: The KnowledgeAgent object to delete. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param agent: The name of the agent to delete or a KnowledgeAgent object. Required. + :type agent: str or ~azure.search.documents.indexes.models.KnowledgeAgent :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.KnowledgeAgent): - agent = args[0] - kwargs.setdefault("etag", agent.e_tag) - return await super().delete_agent(agent.name, **kwargs) - else: - return await super().delete_agent(*args, **kwargs) + try: + name: str = agent.name # type: ignore + return await self._delete_agent( + agent_name=name, + match_condition=match_condition, + etag=agent.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = agent # type: ignore + return await self._delete_agent( + agent_name=name, + **kwargs, + ) @distributed_trace_async async def create_or_update_agent( @@ -436,7 +278,7 @@ async def create_or_update_agent( prefer="return=representation", match_condition=match_condition, etag=agent.e_tag, - **kwargs + **kwargs, ) @distributed_trace_async @@ -464,37 +306,13 @@ async def create_or_update_knowledge_source( prefer="return=representation", match_condition=match_condition, etag=knowledge_source.e_tag, - **kwargs + **kwargs, ) - @overload - async def delete_knowledge_source( - self, - source_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_knowledge_source( self, - knowledge_source: _models.KnowledgeSource, + knowledge_source: Union[str, _models.KnowledgeSource], /, *, match_condition: MatchConditions | None = None, @@ -502,39 +320,28 @@ async def delete_knowledge_source( ) -> None: """Deletes a knowledge source. - :param knowledge_source: The KnowledgeSource object to delete. Required. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace_async - async def delete_knowledge_source(self, *args: Union[str, _models.KnowledgeSource], **kwargs: Any) -> None: - """Deletes a knowledge source. - - :param source_name: The name of the knowledge source to delete. Required. - :type source_name: str - :param knowledge_source: The KnowledgeSource object to delete. - :type knowledge_source: ~azure.search.documents.indexes.models.KnowledgeSource - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param knowledge_source: The name of the knowledge source to delete or a KnowledgeSource object. Required. + :type knowledge_source: str or ~azure.search.documents.indexes.models.KnowledgeSource :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.KnowledgeSource): - knowledge_source = args[0] - kwargs.setdefault("etag", knowledge_source.e_tag) - return await super().delete_knowledge_source(knowledge_source.name, **kwargs) - else: - return await super().delete_knowledge_source(*args, **kwargs) + try: + name: str = knowledge_source.name # type: ignore + return await self._delete_knowledge_source( + source_name=name, + match_condition=match_condition, + etag=knowledge_source.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = knowledge_source # type: ignore + return await self._delete_knowledge_source( + source_name=name, + **kwargs, + ) @distributed_trace def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: @@ -561,7 +368,8 @@ async def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: """ result = await self._get_synonym_maps(**kwargs) assert result.synonym_maps is not None # Hint for mypy - typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + # typed_result = [cast(_models.SynonymMap, x) for x in result.synonym_maps] + typed_result = result.synonym_maps return typed_result @distributed_trace_async @@ -590,34 +398,10 @@ def list_alias_names(self, **kwargs) -> AsyncItemPaged[str]: class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGenerated): """Custom operations mixin for SearchIndexerClient (async).""" - @overload - async def delete_data_source_connection( - self, - data_source_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a data source connection. - - :param data_source_name: The name of the data source connection to delete. Required. - :type data_source_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_data_source_connection( self, - data_source: _models.SearchIndexerDataSourceConnection, + data_source: Union[str, _models.SearchIndexerDataSourceConnection], /, *, match_condition: MatchConditions | None = None, @@ -625,41 +409,28 @@ async def delete_data_source_connection( ) -> None: """Deletes a data source connection. - :param data_source: The SearchIndexerDataSourceConnection object to delete. Required. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection + :param data_source: The name of the data source connection to delete or a SearchIndexerDataSourceConnection object. Required. + :type data_source: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def delete_data_source_connection( - self, *args: Union[str, _models.SearchIndexerDataSourceConnection], **kwargs: Any - ) -> None: - """Deletes a data source connection. - - :param data_source_name: The name of the data source connection to delete. Required. - :type data_source_name: str - :param data_source: The SearchIndexerDataSourceConnection object to delete. - :type data_source: ~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexerDataSourceConnection): - data_source = args[0] - kwargs.setdefault("etag", data_source.e_tag) - return await super().delete_data_source_connection(data_source.name, **kwargs) - else: - return await super().delete_data_source_connection(*args, **kwargs) + try: + name: str = data_source.name # type: ignore + return await self._delete_data_source_connection( + data_source_name=name, + match_condition=match_condition, + etag=data_source.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = data_source # type: ignore + return await self._delete_data_source_connection( + data_source_name=name, + **kwargs, + ) @distributed_trace_async async def create_or_update_data_source_connection( @@ -691,37 +462,13 @@ async def create_or_update_data_source_connection( match_condition=match_condition, etag=data_source.e_tag, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, - **kwargs + **kwargs, ) - @overload - async def delete_indexer( - self, - indexer_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes an indexer. - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_indexer( self, - indexer: _models.SearchIndexer, + indexer: Union[str, _models.SearchIndexer], /, *, match_condition: MatchConditions | None = None, @@ -729,39 +476,28 @@ async def delete_indexer( ) -> None: """Deletes an indexer. - :param indexer: The SearchIndexer object to delete. Required. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer + :param indexer: The name of the indexer to delete or a SearchIndexer object. Required. + :type indexer: str or ~azure.search.documents.indexes.models.SearchIndexer :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def delete_indexer(self, *args: Union[str, _models.SearchIndexer], **kwargs: Any) -> None: - """Deletes an indexer. - - :param indexer_name: The name of the indexer to delete. Required. - :type indexer_name: str - :param indexer: The SearchIndexer object to delete. - :type indexer: ~azure.search.documents.indexes.models.SearchIndexer - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - if args and isinstance(args[0], _models.SearchIndexer): - indexer = args[0] - kwargs.setdefault("etag", indexer.e_tag) - return await super().delete_indexer(indexer.name, **kwargs) - else: - return await super().delete_indexer(*args, **kwargs) + try: + name: str = indexer.name # type: ignore + return await self._delete_indexer( + indexer_name=name, + match_condition=match_condition, + etag=indexer.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = indexer # type: ignore + return await self._delete_indexer( + indexer_name=name, + **kwargs, + ) @distributed_trace_async async def create_or_update_indexer( @@ -798,37 +534,13 @@ async def create_or_update_indexer( etag=indexer.e_tag, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs + **kwargs, ) - @overload - async def delete_skillset( - self, - skillset_name: str, - *, - etag: str | None = None, - match_condition: MatchConditions | None = None, - **kwargs: Any, - ) -> None: - """Deletes a skillset. - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @overload + @distributed_trace_async async def delete_skillset( self, - skillset: _models.SearchIndexerSkillset, + skillset: Union[str, _models.SearchIndexerSkillset], /, *, match_condition: MatchConditions | None = None, @@ -836,39 +548,28 @@ async def delete_skillset( ) -> None: """Deletes a skillset. - :param skillset: The SearchIndexerSkillset object to delete. Required. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - - @distributed_trace_async - async def delete_skillset(self, *args: Union[str, _models.SearchIndexerSkillset], **kwargs: Any) -> None: - """Deletes a skillset. - - :param skillset_name: The name of the skillset to delete. Required. - :type skillset_name: str - :param skillset: The SearchIndexerSkillset object to delete. - :type skillset: ~azure.search.documents.indexes.models.SearchIndexerSkillset - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str + :param skillset: The name of the skillset to delete or a SearchIndexerSkillset object. Required. + :type skillset: str or ~azure.search.documents.indexes.models.SearchIndexerSkillset :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - if args and isinstance(args[0], _models.SearchIndexerSkillset): - skillset = args[0] - kwargs.setdefault("etag", skillset.e_tag) - return await super().delete_skillset(skillset.name, **kwargs) - else: - return await super().delete_skillset(*args, **kwargs) + try: + name: str = skillset.name # type: ignore + return await self._delete_skillset( + skillset_name=name, + match_condition=match_condition, + etag=skillset.e_tag, # type: ignore + **kwargs, + ) + except AttributeError: + name = skillset # type: ignore + return await self._delete_skillset( + skillset_name=name, + **kwargs, + ) @distributed_trace_async async def create_or_update_skillset( @@ -905,25 +606,11 @@ async def create_or_update_skillset( etag=skillset.e_tag, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, disable_cache_reprocessing_change_detection=disable_cache_reprocessing_change_detection, - **kwargs + **kwargs, ) - @overload - async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: - """Lists all skillsets available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: List of all the SearchIndexerSkillsets. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - @distributed_trace_async - async def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: """Lists all skillsets available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -934,27 +621,16 @@ async def get_skillsets(self, **kwargs: Any) -> List[_models.SearchIndexerSkills :rtype: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] :raises ~azure.core.exceptions.HttpResponseError: """ + if select is not None: + kwargs['select'] = ",".join(select) result = await self._get_skillsets(**kwargs) assert result.skillsets is not None # Hint for mypy - typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + # typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] + typed_result = result.skillsets return typed_result - @overload - async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: - """Lists all indexers available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: List of all the SearchIndexers. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] - :raises ~azure.core.exceptions.HttpResponseError: - """ - ... - @distributed_trace_async - async def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: + async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -964,19 +640,13 @@ async def get_indexers(self, **kwargs: Any) -> List[_models.SearchIndexer]: :return: List of all the SearchIndexers. :rtype: list[~azure.search.documents.indexes.models.SearchIndexer] :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_indexers_operations_async.py - :start-after: [START list_indexer_async] - :end-before: [END list_indexer_async] - :language: python - :dedent: 4 - :caption: List all the SearchIndexers """ + if select is not None: + kwargs['select'] = ",".join(select) result = await self._get_indexers(**kwargs) assert result.indexers is not None # Hint for mypy - typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + # typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] + typed_result = result.indexers return typed_result @distributed_trace_async @@ -989,7 +659,7 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: result = await self.get_indexers(**kwargs) return [x.name for x in result] - @overload + @distributed_trace_async async def get_data_source_connections( self, *, select: str | None = None, **kwargs: Any ) -> List[_models.SearchIndexerDataSourceConnection]: @@ -1003,32 +673,12 @@ async def get_data_source_connections( :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] :raises ~azure.core.exceptions.HttpResponseError: """ - ... - - @distributed_trace_async - async def get_data_source_connections(self, **kwargs: Any) -> List[_models.SearchIndexerDataSourceConnection]: - """Lists all data source connections available for a search service. - - :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated - list of JSON property names, or '*' for all properties. The default is all properties. Default - value is None. - :paramtype select: str - :return: List of all the data source connections. - :rtype: list[~azure.search.documents.indexes.models.SearchIndexerDataSourceConnection] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_data_source_operations_async.py - :start-after: [START list_data_source_connection] - :end-before: [END list_data_source_connection] - :language: python - :dedent: 4 - :caption: List all the data source connections - """ + if select is not None: + kwargs['select'] = ",".join(select) result = await self._get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy - typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + # typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] + typed_result = result.data_sources return typed_result @distributed_trace_async diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index 237339026148..175c7f65aae5 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -45,7 +45,7 @@ def _collection_helper(typ) -> str: # Monkey-patch the Collection method onto the enum class -SearchFieldDataType.Collection = staticmethod(_collection_helper) +SearchFieldDataType.Collection = staticmethod(_collection_helper) # type: ignore def Collection(typ) -> str: diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py index 846bf6c3c217..78fd13d0ebcd 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/__init__.py @@ -40,6 +40,7 @@ SearchScoreThreshold, SemanticDebugInfo, SingleVectorFieldResult, + SuggestResult, TextResult, VectorQuery, VectorSimilarityThreshold, @@ -104,6 +105,7 @@ "SearchScoreThreshold", "SemanticDebugInfo", "SingleVectorFieldResult", + "SuggestResult", "TextResult", "VectorQuery", "VectorSimilarityThreshold", diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index 279b344be8e8..d76287449034 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -1348,13 +1348,13 @@ class SuggestDocumentsResult(_Model): """Response containing suggestion query results from an index. :ivar results: The sequence of results returned by the query. Required. - :vartype results: list[~azure.search.documents.models._models.SuggestResult] + :vartype results: list[~azure.search.documents.models.SuggestResult] :ivar coverage: A value indicating the percentage of the index that was included in the query, or null if minimumCoverage was not set in the request. :vartype coverage: float """ - results: list["_models._models.SuggestResult"] = rest_field( + results: list["_models.SuggestResult"] = rest_field( name="value", visibility=["read", "create", "update", "delete", "query"] ) """The sequence of results returned by the query. Required.""" @@ -1368,7 +1368,7 @@ class SuggestDocumentsResult(_Model): def __init__( self, *, - results: list["_models._models.SuggestResult"], + results: list["_models.SuggestResult"], coverage: Optional[float] = None, ) -> None: ... From 549282536122fe5c909ee1d3b5549a8f6f203613 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 29 Oct 2025 13:57:33 -0700 Subject: [PATCH 31/40] update --- .../search/documents/_operations/_patch.py | 79 +++++++++++++++-- .../azure/search/documents/_patch.py | 18 +++- .../documents/aio/_operations/_patch.py | 19 +++-- .../azure/search/documents/aio/_patch.py | 20 ++++- .../documents/indexes/_operations/_patch.py | 84 +++++++------------ .../indexes/aio/_operations/_patch.py | 84 ++++++++----------- .../search/documents/indexes/models/_patch.py | 16 ++-- 7 files changed, 190 insertions(+), 130 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 942b8000a957..36889a14d550 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -21,7 +22,12 @@ def _convert_search_result(result: _models.SearchResult) -> Dict[str, Any]: - """Convert SearchResult model to dictionary with @search.* metadata.""" + """Convert SearchResult model to dictionary with @search.* metadata. + + :param ~azure.search.documents.models.SearchResult result: The search result to convert. + :return: The converted search result. + :rtype: dict + """ ret = dict(result) ret["@search.score"] = result.score ret["@search.reranker_score"] = result.reranker_score @@ -33,7 +39,12 @@ def _convert_search_result(result: _models.SearchResult) -> Dict[str, Any]: def _pack_continuation_token(response: _models.SearchDocumentsResult, api_version: str) -> Optional[bytes]: - """Pack continuation token from search response.""" + """Pack continuation token from search response. + :param ~azure.search.documents.models.SearchDocumentsResult response: The search response. + :param str api_version: The API version used in the request. + :return: The continuation token. + :rtype: bytes or None + """ if response.next_page_parameters is not None: token = { "apiVersion": api_version, @@ -45,7 +56,11 @@ def _pack_continuation_token(response: _models.SearchDocumentsResult, api_versio def _unpack_continuation_token(token: bytes) -> tuple: - """Unpack continuation token to get next link and request.""" + """Unpack continuation token to get next link and request. + :param bytes token: The continuation token to unpack. + :return: A tuple of next link and next page request. + :rtype: tuple[str, ~azure.search.documents.models.SearchRequest] + """ unpacked_token = json.loads(base64.b64decode(token)) next_link = unpacked_token["nextLink"] next_page_parameters = unpacked_token["nextPageParameters"] @@ -54,7 +69,14 @@ def _unpack_continuation_token(token: bytes) -> tuple: def _ensure_response(f): - """Decorator to ensure response is fetched before accessing metadata.""" + # pylint:disable=protected-access + """Decorator to ensure response is fetched before accessing metadata. + :param f: The function to decorate. + :type f: function + + :return: The wrapper function. + :rtype: function + """ def wrapper(self, *args, **kw): if self._current_page is None: @@ -105,9 +127,51 @@ def _build_search_request( debug: Optional[Union[str, _models.QueryDebugMode]] = None, hybrid_search: Optional[_models.HybridSearch] = None, ) -> _models.SearchRequest: + # pylint:disable=too-many-locals """Build a SearchRequest from search parameters. This is a shared helper function used by both sync and async search methods. + + :param str search_text: A full-text search query expression; Use "*" or omit this parameter to search all fields. + :keyword bool include_total_count: A value that specifies whether to fetch the total count of results. + :keyword list[str] facets: The list of facet expressions to apply to the search query. + :keyword str filter: The OData $filter expression to apply to the search query. + :keyword str highlight_fields: The comma-separated list of field names to use for hit highlights. + :keyword str highlight_post_tag: A string tag that is appended to hit highlights. Must be set with highlightPreTag. + :keyword str highlight_pre_tag: A string tag that is prepended to hit highlights. Must be set with highlightPostTag. + :keyword float minimum_coverage: A number between 0 and 100 indicating the percentage of the index that + must be covered by a search query in order for the query to be reported as a success. + :keyword order_by: The list of OData $orderby expressions by which to sort the results. + :keyword query_type: The type of query syntax to use for the search text. + :keyword list[str] scoring_parameters: The list of scoring parameters to use for the search query. + :keyword str scoring_profile: The name of the scoring profile to evaluate match scores for the search query. + :keyword str semantic_query: The semantic query to be used for the search. + :keyword search_fields: The list of field names to search over. + :keyword search_mode: The search mode to use for the search query. + :keyword query_language: The language of the search query. + :keyword query_speller: The type of spell checking to use for the search query. + :keyword query_answer: The type of answers to retrieve for a semantic search query. + :keyword int query_answer_count: The maximum number of answers to retrieve. + :keyword float query_answer_threshold: The confidence score threshold for answers to be included in the results. + :keyword query_caption: The type of captions to retrieve for a semantic search query. + :keyword bool query_caption_highlight_enabled: A value indicating whether caption highlights are enabled. + :keyword semantic_fields: The list of field names to retrieve for semantic search. + :keyword str semantic_configuration_name: The name of the semantic configuration to use for the search. + :keyword select: The list of field names to retrieve in the search results. + :keyword int skip: The number of search results to skip. + :keyword int top: The maximum number of search results to retrieve. + :keyword scoring_statistics: The scoring statistics to retrieve for the search query. + :keyword str session_id: The session ID for the search query. + :keyword list[~azure.search.documents.models.VectorQuery] vector_queries: The list of vector queries to use for the search. + :keyword vector_filter_mode: The vector filter mode to use for the search query. + :keyword semantic_error_mode: The semantic error handling mode to use for the search query. + :keyword int semantic_max_wait_in_milliseconds: The maximum wait time in milliseconds for semantic search. + :keyword query_rewrites: The type of query rewrites to apply for the search query. + :keyword int query_rewrites_count: The maximum number of query rewrites to apply. + :keyword debug: The debug mode for the search query. + :keyword hybrid_search: The hybrid search configuration for the search query. + :return: SearchRequest + :rtype: ~azure.search.documents.models.SearchRequest """ # Convert list parameters to comma-separated strings if needed if isinstance(search_fields, list): @@ -195,10 +259,12 @@ def __init__(self, client, initial_request: _models.SearchRequest, kwargs, conti def _get_next_cb(self, continuation_token): if continuation_token is None: - return self._client._search_post(body=self._initial_request, **self._kwargs) + return self._client._search_post( # pylint:disable=protected-access + body=self._initial_request, **self._kwargs + ) _next_link, next_page_request = _unpack_continuation_token(continuation_token) - return self._client._search_post(body=next_page_request, **self._kwargs) + return self._client._search_post(body=next_page_request, **self._kwargs) # pylint:disable=protected-access def _extract_data_cb(self, response: _models.SearchDocumentsResult): continuation_token = _pack_continuation_token(response, api_version=self._api_version) @@ -513,6 +579,7 @@ def search( hybrid_search: Optional[_models.HybridSearch] = None, **kwargs: Any, ) -> SearchItemPaged[Dict]: + # pylint:disable=too-many-locals """Search the Azure search index for documents. :param str search_text: A full-text search query expression; Use "*" or omit this parameter to diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index 7c7fa989a77f..49fc71698ed1 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -27,12 +27,26 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): class SearchClient(_SearchClient): - """SearchClient customizations go here.""" + """SearchClient.""" def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any ): - super().__init__(endpoint, credential, index_name, **kwargs) + """Initialize SearchClient. + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index e518b79755ac..3cfd90718f1d 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -8,8 +8,6 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ from typing import Any, Dict, List, Optional, Union, cast -import base64 -import json from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator from azure.core.tracing.decorator_async import distributed_trace_async @@ -26,9 +24,15 @@ def _ensure_response(f): - """Decorator to ensure response is fetched before accessing metadata.""" + """Decorator to ensure response is fetched before accessing metadata. + :param f: The function to wrap. + :type f: Callable + :return: The wrapped function. + :rtype: Callable + """ async def wrapper(self, *args, **kw): + # pylint:disable=protected-access if self._current_page is None: self._response = await self._get_next(self.continuation_token) self.continuation_token, self._current_page = await self._extract_data(self._response) @@ -54,10 +58,14 @@ def __init__(self, client, initial_request: _models.SearchRequest, kwargs, conti async def _get_next_cb(self, continuation_token): if continuation_token is None: - return await self._client._search_post(body=self._initial_request, **self._kwargs) + return await self._client._search_post( # pylint:disable=protected-access + body=self._initial_request, **self._kwargs + ) _next_link, next_page_request = _unpack_continuation_token(continuation_token) - return await self._client._search_post(body=next_page_request, **self._kwargs) + return await self._client._search_post( # pylint:disable=protected-access + body=next_page_request, **self._kwargs + ) async def _extract_data_cb(self, response: _models.SearchDocumentsResult): continuation_token = _pack_continuation_token(response, api_version=self._api_version) @@ -376,6 +384,7 @@ async def search( hybrid_search: Optional[_models.HybridSearch] = None, **kwargs: Any, ) -> AsyncSearchItemPaged[Dict]: + # pylint:disable=too-many-locals """Search the Azure search index for documents. :param str search_text: A full-text search query expression; Use "*" or omit this parameter to diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index 5d9f50e649cb..c819ecda2bbc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -7,7 +7,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Union, TYPE_CHECKING +from typing import Any, Union from azure.core.credentials import AzureKeyCredential from azure.core.credentials_async import AsyncTokenCredential from ._client import SearchClient as _SearchClient @@ -15,12 +15,26 @@ class SearchClient(_SearchClient): - """SearchClient customizations go here.""" + """SearchClient.""" def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any ): - super().__init__(endpoint, credential, index_name, **kwargs) + """Initialize SearchClient. + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) __all__: list[str] = [ diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 1e1624c3a7e4..0bb90bd361e4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -8,7 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Iterator, cast, List, Sequence, Union +from typing import Any, cast, List, Sequence, Union, Optional from azure.core import MatchConditions from azure.core.paging import ItemPaged @@ -28,9 +28,8 @@ class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerat def delete_synonym_map( self, synonym_map: Union[str, _models.SynonymMap], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a synonym map. @@ -48,7 +47,7 @@ def delete_synonym_map( return self._delete_synonym_map( synonym_map_name=name, match_condition=match_condition, - etag=synonym_map.e_tag, # type: ignore + etag=synonym_map.e_tag, # type: ignore **kwargs, ) except AttributeError: @@ -62,9 +61,8 @@ def delete_synonym_map( def create_or_update_synonym_map( self, synonym_map: _models.SynonymMap, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SynonymMap: return self._create_or_update_synonym_map( @@ -80,9 +78,8 @@ def create_or_update_synonym_map( def delete_index( self, index: Union[str, _models.SearchIndex], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a search index and all the documents it contains. @@ -114,22 +111,21 @@ def delete_index( def create_or_update_index( self, index: _models.SearchIndex, - allow_index_downtime: bool | None = None, - /, + allow_index_downtime: Optional[bool] = None, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndex: """Creates a new search index or updates an index if it already exists. :param index: The SearchIndex object to create or update. Required. :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters to be added to an index by taking the index offline for at least a few seconds. This temporarily causes indexing and query requests to fail. Performance and write availability of the index can be impaired for several minutes after the index is updated, or longer for very large indexes. Default value is None. - :paramtype allow_index_downtime: bool + :type allow_index_downtime: bool :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: SearchIndex @@ -150,9 +146,8 @@ def create_or_update_index( def create_or_update_alias( self, alias: _models.SearchAlias, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchAlias: """Creates a new search alias or updates an alias if it already exists. @@ -178,9 +173,8 @@ def create_or_update_alias( def delete_alias( self, alias: Union[str, _models.SearchAlias], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a search alias and its associated mapping to an index. @@ -212,9 +206,8 @@ def delete_alias( def delete_agent( self, agent: Union[str, _models.KnowledgeAgent], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a knowledge agent. @@ -246,9 +239,8 @@ def delete_agent( def create_or_update_agent( self, agent: _models.KnowledgeAgent, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.KnowledgeAgent: """Creates a new agent or updates an agent if it already exists. @@ -274,9 +266,8 @@ def create_or_update_agent( def create_or_update_knowledge_source( self, knowledge_source: _models.KnowledgeSource, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.KnowledgeSource: """Creates a new knowledge source or updates a knowledge source if it already exists. @@ -302,9 +293,8 @@ def create_or_update_knowledge_source( def delete_knowledge_source( self, knowledge_source: Union[str, _models.KnowledgeSource], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a knowledge source. @@ -347,10 +337,6 @@ def list_index_names(self, **kwargs: Any) -> ItemPaged[str]: def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: """Lists all synonym maps available for a search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: str :return: List of synonym maps :rtype: list[~azure.search.documents.indexes.models.SynonymMap] :raises ~azure.core.exceptions.HttpResponseError: @@ -392,9 +378,8 @@ class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGen def delete_data_source_connection( self, data_source: Union[str, _models.SearchIndexerDataSourceConnection], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a data source connection. @@ -426,10 +411,9 @@ def delete_data_source_connection( def create_or_update_data_source_connection( self, data_source: _models.SearchIndexerDataSourceConnection, - /, *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - match_condition: MatchConditions | None = None, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndexerDataSourceConnection: """Creates a new data source connection or updates a data source connection if it already exists. @@ -459,9 +443,8 @@ def create_or_update_data_source_connection( def delete_indexer( self, indexer: Union[str, _models.SearchIndexer], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes an indexer. @@ -493,11 +476,10 @@ def delete_indexer( def create_or_update_indexer( self, indexer: _models.SearchIndexer, - /, *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - match_condition: MatchConditions | None = None, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndexer: """Creates a new indexer or updates an indexer if it already exists. @@ -531,9 +513,8 @@ def create_or_update_indexer( def delete_skillset( self, skillset: Union[str, _models.SearchIndexerSkillset], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a skillset. @@ -565,11 +546,10 @@ def delete_skillset( def create_or_update_skillset( self, skillset: _models.SearchIndexerSkillset, - /, *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - match_condition: MatchConditions | None = None, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndexerSkillset: """Creates a new skillset in a search service or updates the skillset if it already exists. @@ -600,7 +580,7 @@ def create_or_update_skillset( ) @distributed_trace - def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + def get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: """Lists all skillsets available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -612,7 +592,7 @@ def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_mo :raises ~azure.core.exceptions.HttpResponseError: """ if select is not None: - kwargs['select'] = ",".join(select) + kwargs["select"] = ",".join(select) result = self._get_skillsets(**kwargs) assert result.skillsets is not None # Hint for mypy # typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] @@ -620,7 +600,7 @@ def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_mo return typed_result @distributed_trace - def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: + def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> List[_models.SearchIndexer]: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -632,7 +612,7 @@ def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_mod :raises ~azure.core.exceptions.HttpResponseError: """ if select is not None: - kwargs['select'] = ",".join(select) + kwargs["select"] = ",".join(select) result = self._get_indexers(**kwargs) assert result.indexers is not None # Hint for mypy # typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] @@ -660,7 +640,7 @@ def get_indexer_names(self, **kwargs: Any) -> Sequence[str]: @distributed_trace def get_data_source_connections( - self, *, select: str | None = None, **kwargs: Any + self, *, select: Optional[str] = None, **kwargs: Any ) -> List[_models.SearchIndexerDataSourceConnection]: """Lists all data source connections available for a search service. @@ -673,7 +653,7 @@ def get_data_source_connections( :raises ~azure.core.exceptions.HttpResponseError: """ if select is not None: - kwargs['select'] = ",".join(select) + kwargs["select"] = ",".join(select) result = self._get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy # typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index ad47b35466eb..a07aba8edbd4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -8,7 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, AsyncIterator, cast, List, Sequence, Union +from typing import Any, cast, List, Sequence, Union, Optional from azure.core import MatchConditions from azure.core.async_paging import AsyncItemPaged @@ -29,9 +29,8 @@ class _SearchIndexClientOperationsMixin(_SearchIndexClientOperationsMixinGenerat async def delete_synonym_map( self, synonym_map: Union[str, _models.SynonymMap], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a synonym map. @@ -63,9 +62,8 @@ async def delete_synonym_map( async def create_or_update_synonym_map( self, synonym_map: _models.SynonymMap, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SynonymMap: """Creates a new synonym map or updates a synonym map if it already exists. @@ -91,9 +89,8 @@ async def create_or_update_synonym_map( async def delete_index( self, index: Union[str, _models.SearchIndex], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a search index and all the documents it contains. @@ -125,22 +122,21 @@ async def delete_index( async def create_or_update_index( self, index: _models.SearchIndex, - allow_index_downtime: bool | None = None, - /, + allow_index_downtime: Optional[bool] = None, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndex: """Creates a new search index or updates an index if it already exists. :param index: The SearchIndex object to create or update. Required. :type index: ~azure.search.documents.indexes.models.SearchIndex - :keyword allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters + :param allow_index_downtime: Allows new analyzers, tokenizers, token filters, or char filters to be added to an index by taking the index offline for at least a few seconds. This temporarily causes indexing and query requests to fail. Performance and write availability of the index can be impaired for several minutes after the index is updated, or longer for very large indexes. Default value is None. - :paramtype allow_index_downtime: bool + :type allow_index_downtime: bool :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: SearchIndex @@ -161,9 +157,8 @@ async def create_or_update_index( async def create_or_update_alias( self, alias: _models.SearchAlias, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchAlias: """Creates a new search alias or updates an alias if it already exists. @@ -189,9 +184,8 @@ async def create_or_update_alias( async def delete_alias( self, alias: Union[str, _models.SearchAlias], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a search alias and its associated mapping to an index. @@ -223,9 +217,8 @@ async def delete_alias( async def delete_agent( self, agent: Union[str, _models.KnowledgeAgent], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a knowledge agent. @@ -257,9 +250,8 @@ async def delete_agent( async def create_or_update_agent( self, agent: _models.KnowledgeAgent, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.KnowledgeAgent: """Creates a new agent or updates an agent if it already exists. @@ -285,9 +277,8 @@ async def create_or_update_agent( async def create_or_update_knowledge_source( self, knowledge_source: _models.KnowledgeSource, - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.KnowledgeSource: """Creates a new knowledge source or updates a knowledge source if it already exists. @@ -313,9 +304,8 @@ async def create_or_update_knowledge_source( async def delete_knowledge_source( self, knowledge_source: Union[str, _models.KnowledgeSource], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a knowledge source. @@ -358,10 +348,6 @@ def list_index_names(self, **kwargs: Any) -> AsyncItemPaged[str]: async def get_synonym_maps(self, **kwargs: Any) -> List[_models.SynonymMap]: """Lists all synonym maps available for a search service. - :keyword select: Selects which top-level properties to retrieve. Specified as a - comma-separated list of JSON property names, or '*' for all properties. The default is all - properties. - :paramtype select: str :return: List of synonym maps :rtype: list[~azure.search.documents.indexes.models.SynonymMap] :raises ~azure.core.exceptions.HttpResponseError: @@ -402,9 +388,8 @@ class _SearchIndexerClientOperationsMixin(_SearchIndexerClientOperationsMixinGen async def delete_data_source_connection( self, data_source: Union[str, _models.SearchIndexerDataSourceConnection], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a data source connection. @@ -436,10 +421,9 @@ async def delete_data_source_connection( async def create_or_update_data_source_connection( self, data_source: _models.SearchIndexerDataSourceConnection, - /, *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - match_condition: MatchConditions | None = None, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndexerDataSourceConnection: """Creates a new data source connection or updates a data source connection if it already exists. @@ -469,9 +453,8 @@ async def create_or_update_data_source_connection( async def delete_indexer( self, indexer: Union[str, _models.SearchIndexer], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes an indexer. @@ -503,11 +486,10 @@ async def delete_indexer( async def create_or_update_indexer( self, indexer: _models.SearchIndexer, - /, *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - match_condition: MatchConditions | None = None, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndexer: """Creates a new indexer or updates an indexer if it already exists. @@ -541,9 +523,8 @@ async def create_or_update_indexer( async def delete_skillset( self, skillset: Union[str, _models.SearchIndexerSkillset], - /, *, - match_condition: MatchConditions | None = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: """Deletes a skillset. @@ -575,11 +556,10 @@ async def delete_skillset( async def create_or_update_skillset( self, skillset: _models.SearchIndexerSkillset, - /, *, - skip_indexer_reset_requirement_for_cache: bool | None = None, - disable_cache_reprocessing_change_detection: bool | None = None, - match_condition: MatchConditions | None = None, + skip_indexer_reset_requirement_for_cache: Optional[bool] = None, + disable_cache_reprocessing_change_detection: Optional[bool] = None, + match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> _models.SearchIndexerSkillset: """Creates a new skillset in a search service or updates the skillset if it already exists. @@ -610,7 +590,9 @@ async def create_or_update_skillset( ) @distributed_trace_async - async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexerSkillset]: + async def get_skillsets( + self, *, select: Optional[str] = None, **kwargs: Any + ) -> List[_models.SearchIndexerSkillset]: """Lists all skillsets available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -622,7 +604,7 @@ async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> Li :raises ~azure.core.exceptions.HttpResponseError: """ if select is not None: - kwargs['select'] = ",".join(select) + kwargs["select"] = ",".join(select) result = await self._get_skillsets(**kwargs) assert result.skillsets is not None # Hint for mypy # typed_result = [cast(_models.SearchIndexerSkillset, x) for x in result.skillsets] @@ -630,7 +612,7 @@ async def get_skillsets(self, *, select: str | None = None, **kwargs: Any) -> Li return typed_result @distributed_trace_async - async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> List[_models.SearchIndexer]: + async def get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> List[_models.SearchIndexer]: """Lists all indexers available for a search service. :keyword select: Selects which top-level properties to retrieve. Specified as a comma-separated @@ -642,7 +624,7 @@ async def get_indexers(self, *, select: str | None = None, **kwargs: Any) -> Lis :raises ~azure.core.exceptions.HttpResponseError: """ if select is not None: - kwargs['select'] = ",".join(select) + kwargs["select"] = ",".join(select) result = await self._get_indexers(**kwargs) assert result.indexers is not None # Hint for mypy # typed_result = [cast(_models.SearchIndexer, x) for x in result.indexers] @@ -661,7 +643,7 @@ async def get_indexer_names(self, **kwargs) -> Sequence[str]: @distributed_trace_async async def get_data_source_connections( - self, *, select: str | None = None, **kwargs: Any + self, *, select: Optional[str] = None, **kwargs: Any ) -> List[_models.SearchIndexerDataSourceConnection]: """Lists all data source connections available for a search service. @@ -674,7 +656,7 @@ async def get_data_source_connections( :raises ~azure.core.exceptions.HttpResponseError: """ if select is not None: - kwargs['select'] = ",".join(select) + kwargs["select"] = ",".join(select) result = await self._get_data_source_connections(**kwargs) assert result.data_sources is not None # Hint for mypy # typed_result = [cast(_models.SearchIndexerDataSourceConnection, x) for x in result.data_sources] diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py index 175c7f65aae5..56ece1255f33 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_patch.py @@ -9,19 +9,9 @@ """ from typing import Any, Dict, List, Optional, Union -from ._models import ( - SearchField as _SearchField, - SearchIndexerDataSourceConnection as _SearchIndexerDataSourceConnection, - SearchIndexerDataContainer, - SearchIndexerDataIdentity, - SearchResourceEncryptionKey, - DataChangeDetectionPolicy, - DataDeletionDetectionPolicy, - DataSourceCredentials, -) +from ._models import SearchField as _SearchField from ._enums import ( LexicalAnalyzerName, - IndexerPermissionOption, SearchFieldDataType as _SearchFieldDataType, PermissionFilter, VectorEncodingFormat, @@ -36,7 +26,9 @@ def _collection_helper(typ) -> str: """Helper function to create a collection type string. :param typ: The type to wrap in a collection. Can be a string or an enum value. + :type typ: str or Enum :return: A collection type string. + :rtype: str """ # If typ is an enum, get its value; otherwise use it as-is if hasattr(typ, "value"): @@ -52,7 +44,9 @@ def Collection(typ) -> str: """Helper function to create a collection type string. :param typ: The type to wrap in a collection. Can be a string or an enum value. + :type typ: str or Enum :return: A collection type string. + :rtype: str """ # If typ is an enum, get its value; otherwise use it as-is if hasattr(typ, "value"): From 69b62f118c7fb8d893f98074917fe2445395ab61 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 29 Oct 2025 14:09:22 -0700 Subject: [PATCH 32/40] update --- .../search/documents/_operations/_patch.py | 1 + .../azure/search/documents/_patch.py | 31 +++++++++-------- .../documents/aio/_operations/_patch.py | 1 + .../azure/search/documents/aio/_patch.py | 33 +++++++++---------- 4 files changed, 33 insertions(+), 33 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 36889a14d550..21f3f8a123a7 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -310,6 +310,7 @@ class SearchItemPaged(ItemPaged[Dict]): """A pageable list of search results with metadata accessors.""" def __init__(self, page_iterator_factory_func) -> None: + super(SearchItemPaged, self).__init__() # Store the factory function that creates SearchPageIterator instances self._page_iterator_factory = page_iterator_factory_func self._first_page_iterator_instance: Optional[SearchPageIterator] = None diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index 49fc71698ed1..568c5393befc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -27,25 +27,24 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): class SearchClient(_SearchClient): - """SearchClient.""" + """SearchClient. + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any - ): - """Initialize SearchClient. - :param endpoint: Service host. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Is either a key - credential type or a token credential type. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential or - ~azure.core.credentials.TokenCredential - :param index_name: The name of the index. Required. - :type index_name: str - :keyword api_version: The API version to use for this operation. Default value is - "2025-11-01-preview". Note that overriding this default value may result in unsupported - behavior. - :paramtype api_version: str - """ + ) -> None: super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 3cfd90718f1d..d2aa4f9c2809 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -111,6 +111,7 @@ class AsyncSearchItemPaged(AsyncItemPaged[Dict]): """An async pageable list of search results with metadata accessors.""" def __init__(self, page_iterator_factory_func) -> None: + super(AsyncSearchItemPaged, self).__init__() # Store the factory function that creates AsyncSearchPageIterator instances self._page_iterator_factory = page_iterator_factory_func self._first_page_iterator_instance: Optional[AsyncSearchPageIterator] = None diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index c819ecda2bbc..1a2596ae9753 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -15,25 +15,24 @@ class SearchClient(_SearchClient): - """SearchClient.""" - + """SearchClient. + + :param endpoint: Service host. Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :param index_name: The name of the index. Required. + :type index_name: str + :keyword api_version: The API version to use for this operation. Default value is + "2025-11-01-preview". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any - ): - """Initialize SearchClient. - :param endpoint: Service host. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Is either a key - credential type or a token credential type. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential or - ~azure.core.credentials_async.AsyncTokenCredential - :param index_name: The name of the index. Required. - :type index_name: str - :keyword api_version: The API version to use for this operation. Default value is - "2025-11-01-preview". Note that overriding this default value may result in unsupported - behavior. - :paramtype api_version: str - """ + ) -> None: super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) From af14df0278294afc745ed8c1a549750fbb069272 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 29 Oct 2025 16:32:16 -0700 Subject: [PATCH 33/40] updates --- .../azure/search/documents/_operations/_patch.py | 6 +++--- .../azure/search/documents/aio/_operations/_patch.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index 21f3f8a123a7..ef895010c1d8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -13,7 +13,7 @@ import itertools import json -from azure.core.paging import ItemPaged, PageIterator +from azure.core.paging import ItemPaged, PageIterator, ReturnType from azure.core.tracing.decorator import distributed_trace from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated @@ -306,7 +306,7 @@ def get_debug_info(self) -> Optional[_models.DebugInfo]: return response.debug_info -class SearchItemPaged(ItemPaged[Dict]): +class SearchItemPaged(ItemPaged[ReturnType]): """A pageable list of search results with metadata accessors.""" def __init__(self, page_iterator_factory_func) -> None: @@ -327,7 +327,7 @@ def by_page(self, continuation_token=None): """ return self._page_iterator_factory(continuation_token) - def __next__(self) -> Dict: + def __next__(self) -> ReturnType: if self._page_iterator is None: first_iterator = self._first_iterator_instance() self._page_iterator = itertools.chain.from_iterable(first_iterator) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index d2aa4f9c2809..408543fb5cde 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -9,7 +9,7 @@ """ from typing import Any, Dict, List, Optional, Union, cast -from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator +from azure.core.async_paging import AsyncItemPaged, AsyncPageIterator, ReturnType from azure.core.tracing.decorator_async import distributed_trace_async from ._operations import _SearchClientOperationsMixin as _SearchClientOperationsMixinGenerated @@ -107,7 +107,7 @@ async def get_debug_info(self) -> Optional[_models.DebugInfo]: return response.debug_info -class AsyncSearchItemPaged(AsyncItemPaged[Dict]): +class AsyncSearchItemPaged(AsyncItemPaged[ReturnType]): """An async pageable list of search results with metadata accessors.""" def __init__(self, page_iterator_factory_func) -> None: @@ -128,7 +128,7 @@ def by_page(self, continuation_token=None): """ return self._page_iterator_factory(continuation_token) - async def __anext__(self) -> Dict: + async def __anext__(self) -> ReturnType: if self._page_iterator is None: self._page_iterator = self.by_page() if self._page is None: From b2b46372893444969d65aa0af193ea4542abd950 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Thu, 30 Oct 2025 08:46:38 -0700 Subject: [PATCH 34/40] update --- .../azure/search/documents/aio/_patch.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index 1a2596ae9753..313397192a0f 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -16,7 +16,7 @@ class SearchClient(_SearchClient): """SearchClient. - + :param endpoint: Service host. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Is either a key @@ -30,6 +30,7 @@ class SearchClient(_SearchClient): behavior. :paramtype api_version: str """ + def __init__( self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any ) -> None: From ab33d6d51237120145958094c5bc72ea10ec4465 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Thu, 30 Oct 2025 10:45:02 -0700 Subject: [PATCH 35/40] update --- .../search/documents/indexes/_operations/_patch.py | 2 +- .../test_search_index_client_live_async.py | 6 +++--- .../tests/test_search_client_search_live.py | 12 ++++++++---- .../tests/test_search_index_client_live.py | 6 +++--- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 0bb90bd361e4..07d2bd36f184 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -66,7 +66,7 @@ def create_or_update_synonym_map( **kwargs: Any, ) -> _models.SynonymMap: return self._create_or_update_synonym_map( - name=synonym_map.name, + synonym_map_name=synonym_map.name, synonym_map=synonym_map, prefer="return=representation", etag=synonym_map.e_tag, diff --git a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py index 00f99e9a47c0..7d1e44b43930 100644 --- a/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py +++ b/sdk/search/azure-search-documents/tests/async_tests/test_search_index_client_live_async.py @@ -88,9 +88,9 @@ async def _test_get_index(self, client, index_name): async def _test_get_index_statistics(self, client, index_name): result = await client.get_index_statistics(index_name) keys = set(result.keys()) - assert "document_count" in keys - assert "storage_size" in keys - assert "vector_index_size" in keys + assert "documentCount" in keys + assert "storageSize" in keys + assert "vectorIndexSize" in keys async def _test_delete_indexes_if_unchanged(self, client): # First create an index diff --git a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py index e52e8c806da0..de3325cbe356 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client_search_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_client_search_live.py @@ -124,10 +124,14 @@ def _test_get_search_facets_result(self, client): def _test_autocomplete(self, client): results = client.autocomplete(search_text="mot", suggester_name="sg") - assert any(d.get('text') == 'motel' for d in results) - assert any(d.get('query_plus_text') == 'motel' for d in results) + assert any(d.text == 'motel' for d in results) + assert any(d.query_plus_text == 'motel' for d in results) def _test_suggest(self, client): results = client.suggest(search_text="mot", suggester_name="sg") - assert {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."} in results - assert {"hotelId": "9", "text": "Secret Point Motel"} in results + result = results[0] + assert result["hotelId"] == "2" + assert result.text == "Cheapest hotel in town. Infact, a motel." + result = results[1] + assert result["hotelId"] == "9" + assert result.text == "Secret Point Motel" diff --git a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py index 0644e0be8423..f07f8d01d7e8 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client_live.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client_live.py @@ -64,9 +64,9 @@ def _test_get_index(self, client, index_name): def _test_get_index_statistics(self, client, index_name): result = client.get_index_statistics(index_name) keys = set(result.keys()) - assert "document_count" in keys - assert "storage_size" in keys - assert "vector_index_size" in keys + assert "documentCount" in keys + assert "storageSize" in keys + assert "vectorIndexSize" in keys def _test_create_index(self, client, index_name): fields = [ From 517f68e1916ed783fd33fa69f8d6a8caf51781a1 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 31 Oct 2025 09:13:33 -0700 Subject: [PATCH 36/40] update --- .../documents/_operations/_operations.py | 7 --- .../documents/aio/_operations/_operations.py | 7 --- .../indexes/_operations/_operations.py | 45 ------------------- .../indexes/aio/_operations/_operations.py | 45 ------------------- .../knowledgebase/_operations/_operations.py | 15 ------- .../aio/_operations/_operations.py | 15 ------- 6 files changed, 134 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index fd081ab470ab..8b3573601df4 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -32,7 +32,6 @@ from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -from .._validation import api_version_validation JSON = MutableMapping[str, Any] _Unset: Any = object() @@ -564,12 +563,6 @@ def get_document_count(self, *, query_source_authorization: Optional[str] = None return deserialized # type: ignore @distributed_trace - @api_version_validation( - params_added_on={ - "2025-08-01-preview": ["query_rewrites", "debug", "query_language", "speller", "semantic_fields"] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) def _search_get( self, *, diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index 2238afb1bea7..5edbfcacfc01 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -41,7 +41,6 @@ ) from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.utils import ClientMixinABC -from ..._validation import api_version_validation from .._configuration import SearchClientConfiguration JSON = MutableMapping[str, Any] @@ -119,12 +118,6 @@ async def get_document_count(self, *, query_source_authorization: Optional[str] return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - params_added_on={ - "2025-08-01-preview": ["query_rewrites", "debug", "query_language", "speller", "semantic_fields"] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) async def _search_get( self, *, diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index b73bfd6358ac..3a306e010626 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -35,7 +35,6 @@ from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Serializer from ..._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match -from ..._validation import api_version_validation from .._configuration import SearchIndexClientConfiguration, SearchIndexerClientConfiguration JSON = MutableMapping[str, Any] @@ -4097,11 +4096,6 @@ def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatist return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) def list_index_stats_summary(self, **kwargs: Any) -> ItemPaged["_models1.IndexStatisticsSummary"]: """Retrieves a summary of statistics for all indexes in the search service. @@ -4228,10 +4222,6 @@ def _create_or_update_data_source_connection( ) -> _models1.SearchIndexerDataSourceConnection: ... @distributed_trace - @api_version_validation( - params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) def _create_or_update_data_source_connection( self, data_source_name: str, @@ -4715,11 +4705,6 @@ def reset_indexer(self, indexer_name: str, **kwargs: Any) -> None: # pylint: di return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Resync selective options from the datasource to be re-ingested by the indexer.". @@ -4856,13 +4841,6 @@ def reset_documents( """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) def reset_documents( # pylint: disable=inconsistent-return-statements self, indexer_name: str, @@ -5032,15 +5010,6 @@ def _create_or_update_indexer( ) -> _models1.SearchIndexer: ... @distributed_trace - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) def _create_or_update_indexer( self, indexer_name: str, @@ -5565,15 +5534,6 @@ def _create_or_update_skillset( ) -> _models1.SearchIndexerSkillset: ... @distributed_trace - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) def _create_or_update_skillset( self, skillset_name: str, @@ -6064,11 +6024,6 @@ def reset_skills( """ @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) def reset_skills( # pylint: disable=inconsistent-return-statements self, skillset_name: str, skill_names: Union[_models1.SkillNames, JSON, IO[bytes]], **kwargs: Any ) -> None: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index 974305d5c5b6..aadec4d056c8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -35,7 +35,6 @@ from .... import models as _models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ...._utils.utils import ClientMixinABC -from ...._validation import api_version_validation from ..._operations._operations import ( build_search_index_analyze_text_request, build_search_index_create_agent_request, @@ -2756,11 +2755,6 @@ async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceS return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "accept"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) def list_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged["_models2.IndexStatisticsSummary"]: """Retrieves a summary of statistics for all indexes in the search service. @@ -2887,10 +2881,6 @@ async def _create_or_update_data_source_connection( ) -> _models2.SearchIndexerDataSourceConnection: ... @distributed_trace_async - @api_version_validation( - params_added_on={"2025-08-01-preview": ["skip_indexer_reset_requirement_for_cache"]}, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) async def _create_or_update_data_source_connection( self, data_source_name: str, @@ -3374,11 +3364,6 @@ async def reset_indexer(self, indexer_name: str, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "indexer_name"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) async def resync(self, indexer_name: str, **kwargs: Any) -> None: """Resync selective options from the datasource to be re-ingested by the indexer.". @@ -3515,13 +3500,6 @@ async def reset_documents( """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={ - "2025-08-01-preview": ["api_version", "overwrite", "client_request_id", "indexer_name", "content_type"] - }, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) async def reset_documents( self, indexer_name: str, @@ -3691,15 +3669,6 @@ async def _create_or_update_indexer( ) -> _models2.SearchIndexer: ... @distributed_trace_async - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) async def _create_or_update_indexer( self, indexer_name: str, @@ -4226,15 +4195,6 @@ async def _create_or_update_skillset( ) -> _models2.SearchIndexerSkillset: ... @distributed_trace_async - @api_version_validation( - params_added_on={ - "2025-08-01-preview": [ - "skip_indexer_reset_requirement_for_cache", - "disable_cache_reprocessing_change_detection", - ] - }, - api_versions_list=["2025-09-01", "2025-08-01-preview", "2025-11-01-preview"], - ) async def _create_or_update_skillset( self, skillset_name: str, @@ -4727,11 +4687,6 @@ async def reset_skills( """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-08-01-preview", - params_added_on={"2025-08-01-preview": ["api_version", "client_request_id", "skillset_name", "content_type"]}, - api_versions_list=["2025-08-01-preview", "2025-11-01-preview"], - ) async def reset_skills( self, skillset_name: str, skill_names: Union[_models2.SkillNames, JSON, IO[bytes]], **kwargs: Any ) -> None: diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py index dd6310f3cedb..cb886956afd9 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_operations/_operations.py @@ -30,7 +30,6 @@ from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Serializer from ..._utils.utils import ClientMixinABC -from ..._validation import api_version_validation from .._configuration import KnowledgeBaseRetrievalClientConfiguration JSON = MutableMapping[str, Any] @@ -167,20 +166,6 @@ def retrieve( """ @distributed_trace - @api_version_validation( - method_added_on="2025-11-01-preview", - params_added_on={ - "2025-11-01-preview": [ - "api_version", - "knowledge_base_name", - "query_source_authorization", - "client_request_id", - "content_type", - "accept", - ] - }, - api_versions_list=["2025-11-01-preview"], - ) def retrieve( self, knowledge_base_name: str, diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py index 0cab3bd0412e..311449599dc6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_operations/_operations.py @@ -30,7 +30,6 @@ from ... import models as _models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.utils import ClientMixinABC -from ...._validation import api_version_validation from ..._operations._operations import build_knowledge_base_retrieval_retrieve_request from .._configuration import KnowledgeBaseRetrievalClientConfiguration @@ -132,20 +131,6 @@ async def retrieve( """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-11-01-preview", - params_added_on={ - "2025-11-01-preview": [ - "api_version", - "knowledge_base_name", - "query_source_authorization", - "client_request_id", - "content_type", - "accept", - ] - }, - api_versions_list=["2025-11-01-preview"], - ) async def retrieve( self, knowledge_base_name: str, From e8a5ddb5ed17832a587c3d74a0adccde3f511786 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 31 Oct 2025 11:34:45 -0700 Subject: [PATCH 37/40] update --- .../documents/_operations/_operations.py | 45 +- .../azure/search/documents/_patch.py | 7 +- .../documents/aio/_operations/_operations.py | 45 +- .../indexes/_operations/_operations.py | 519 ++++++++++++------ .../documents/indexes/_operations/_patch.py | 48 +- .../indexes/aio/_operations/_operations.py | 473 ++++++++++------ .../indexes/aio/_operations/_patch.py | 48 +- .../documents/indexes/models/__init__.py | 22 +- .../search/documents/indexes/models/_enums.py | 17 +- .../documents/indexes/models/_models.py | 245 ++------- 10 files changed, 843 insertions(+), 626 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index 8b3573601df4..f462aa29f982 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -549,7 +549,10 @@ def get_document_count(self, *, query_source_authorization: Optional[str] = None except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -822,7 +825,10 @@ def _search_get( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1171,7 +1177,10 @@ def _search_post( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1249,7 +1258,10 @@ def get_document( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1384,7 +1396,10 @@ def _suggest_get( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1580,7 +1595,10 @@ def _suggest_post( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1693,7 +1711,10 @@ def _index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1820,7 +1841,10 @@ def _autocomplete_get( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2006,7 +2030,10 @@ def _autocomplete_post( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models1.ErrorResponse, response) + error = _failsafe_deserialize( + _models1.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index 568c5393befc..722b424cb1fb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -17,13 +17,10 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - V2020_06_30 = "2020-06-30" - V2023_11_01 = "2023-11-01" - V2024_07_01 = "2024-07-01" - V2025_08_01_PREVIEW = "2025-08-01-preview" + V2025_11_01_PREVIEW = "2025-11-01-preview" -DEFAULT_VERSION = ApiVersion.V2025_08_01_PREVIEW +DEFAULT_VERSION = ApiVersion.V2025_11_01_PREVIEW class SearchClient(_SearchClient): diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index 5edbfcacfc01..f2943145d805 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -104,7 +104,10 @@ async def get_document_count(self, *, query_source_authorization: Optional[str] except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -377,7 +380,10 @@ async def _search_get( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -726,7 +732,10 @@ async def _search_post( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -804,7 +813,10 @@ async def get_document( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -939,7 +951,10 @@ async def _suggest_get( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1135,7 +1150,10 @@ async def _suggest_post( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1248,7 +1266,10 @@ async def _index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1375,7 +1396,10 @@ async def _autocomplete_get( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1561,7 +1585,10 @@ async def _autocomplete_post( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py index 3a306e010626..4f07cf56d8fb 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_operations.py @@ -55,7 +55,7 @@ def build_search_index_create_or_update_synonym_map_request( # pylint: disable= _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -202,7 +202,7 @@ def build_search_index_create_or_update_index_request( # pylint: disable=name-t _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -419,7 +419,7 @@ def build_search_index_create_or_update_alias_request( # pylint: disable=name-t _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -544,21 +544,25 @@ def build_search_index_create_alias_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_create_or_update_agent_request( # pylint: disable=name-too-long - agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_index_create_or_update_knowledge_base_request( # pylint: disable=name-too-long + knowledge_base_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/agents('{agentName}')" + _url = "/knowledgebases('{knowledgeBaseName}')" path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -581,17 +585,21 @@ def build_search_index_create_or_update_agent_request( # pylint: disable=name-t return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_delete_agent_request( - agent_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any +def build_search_index_delete_knowledge_base_request( # pylint: disable=name-too-long + knowledge_base_name: str, + *, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) # Construct URL - _url = "/agents('{agentName}')" + _url = "/knowledgebases('{knowledgeBaseName}')" path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -610,7 +618,9 @@ def build_search_index_delete_agent_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_get_agent_request(agent_name: str, **kwargs: Any) -> HttpRequest: +def build_search_index_get_knowledge_base_request( # pylint: disable=name-too-long + knowledge_base_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -618,9 +628,9 @@ def build_search_index_get_agent_request(agent_name: str, **kwargs: Any) -> Http accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/agents('{agentName}')" + _url = "/knowledgebases('{knowledgeBaseName}')" path_format_arguments = { - "agentName": _SERIALIZER.url("agent_name", agent_name, "str"), + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -634,7 +644,7 @@ def build_search_index_get_agent_request(agent_name: str, **kwargs: Any) -> Http return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_list_agents_request(**kwargs: Any) -> HttpRequest: +def build_search_index_list_knowledge_bases_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -642,7 +652,7 @@ def build_search_index_list_agents_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/agents" + _url = "/knowledgebases" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -653,7 +663,7 @@ def build_search_index_list_agents_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_search_index_create_agent_request(**kwargs: Any) -> HttpRequest: +def build_search_index_create_knowledge_base_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -662,7 +672,7 @@ def build_search_index_create_agent_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/agents" + _url = "/knowledgebases" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -681,7 +691,7 @@ def build_search_index_create_or_update_knowledge_source_request( # pylint: dis _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -857,7 +867,7 @@ def build_search_indexer_create_or_update_data_source_connection_request( # pyl _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -1103,7 +1113,7 @@ def build_search_indexer_create_or_update_indexer_request( # pylint: disable=na _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -1278,7 +1288,7 @@ def build_search_indexer_create_or_update_skillset_request( # pylint: disable=n _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-01-preview")) accept = _headers.pop("Accept", "application/json") @@ -1524,7 +1534,7 @@ def _create_or_update_synonym_map( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SynonymMap] = kwargs.pop("cls", None) @@ -1565,7 +1575,10 @@ def _create_or_update_synonym_map( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1641,7 +1654,10 @@ def _delete_synonym_map( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -1695,7 +1711,10 @@ def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models1.Syno except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1760,7 +1779,10 @@ def _get_synonym_maps( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1883,7 +1905,10 @@ def create_synonym_map( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1991,7 +2016,7 @@ def _create_or_update_index( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SearchIndex] = kwargs.pop("cls", None) @@ -2034,7 +2059,10 @@ def _create_or_update_index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2118,7 +2146,10 @@ def _delete_index( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -2179,7 +2210,10 @@ def get_index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2273,7 +2307,10 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2386,7 +2423,10 @@ def create_index(self, index: Union[_models1.SearchIndex, JSON, IO[bytes]], **kw except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2455,7 +2495,10 @@ def get_index_statistics( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2625,7 +2668,10 @@ def analyze_text( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2715,7 +2761,7 @@ def _create_or_update_alias( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SearchAlias] = kwargs.pop("cls", None) @@ -2756,7 +2802,10 @@ def _create_or_update_alias( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2833,7 +2882,10 @@ def _delete_alias( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -2887,7 +2939,10 @@ def get_alias(self, alias_name: str, **kwargs: Any) -> _models1.SearchAlias: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2976,7 +3031,10 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3089,7 +3147,10 @@ def create_alias(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kw except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3103,64 +3164,63 @@ def create_alias(self, alias: Union[_models1.SearchAlias, JSON, IO[bytes]], **kw return deserialized # type: ignore @overload - def _create_or_update_agent( + def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: _models1.KnowledgeAgent, + knowledge_base_name: str, + knowledge_base: _models1.KnowledgeBase, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: ... + ) -> _models1.KnowledgeBase: ... @overload - def _create_or_update_agent( + def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: JSON, + knowledge_base_name: str, + knowledge_base: JSON, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: ... + ) -> _models1.KnowledgeBase: ... @overload - def _create_or_update_agent( + def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: IO[bytes], + knowledge_base_name: str, + knowledge_base: IO[bytes], *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: ... + ) -> _models1.KnowledgeBase: ... @distributed_trace - def _create_or_update_agent( + def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], + knowledge_base_name: str, + knowledge_base: Union[_models1.KnowledgeBase, JSON, IO[bytes]], *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, - ) -> _models1.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Is one of the - following types: KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param knowledge_base: The definition of the knowledge base to create or update. Is one of the + following types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3180,19 +3240,19 @@ def _create_or_update_agent( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeBase] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_create_or_update_agent_request( - agent_name=agent_name, + _request = build_search_index_create_or_update_knowledge_base_request( + knowledge_base_name=knowledge_base_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -3214,20 +3274,23 @@ def _create_or_update_agent( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: response.read() # Load the body in memory and close the socket except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models1.KnowledgeBase, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3235,19 +3298,18 @@ def _create_or_update_agent( return deserialized # type: ignore @distributed_trace - def _delete_agent( # pylint: disable=inconsistent-return-statements + def _delete_knowledge_base( # pylint: disable=inconsistent-return-statements self, - agent_name: str, + knowledge_base_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any, ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. + """Deletes a knowledge base. - :param agent_name: The name of the agent. Required. - :type agent_name: str + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -3276,8 +3338,8 @@ def _delete_agent( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_search_index_delete_agent_request( - agent_name=agent_name, + _request = build_search_index_delete_knowledge_base_request( + knowledge_base_name=knowledge_base_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -3298,20 +3360,23 @@ def _delete_agent( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get_agent(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: - """Retrieves an agent definition. + def get_knowledge_base(self, knowledge_base_name: str, **kwargs: Any) -> _models1.KnowledgeBase: + """Retrieves a knowledge base definition. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3325,10 +3390,10 @@ def get_agent(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeBase] = kwargs.pop("cls", None) - _request = build_search_index_get_agent_request( - agent_name=agent_name, + _request = build_search_index_get_knowledge_base_request( + knowledge_base_name=knowledge_base_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3352,13 +3417,16 @@ def get_agent(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models1.KnowledgeBase, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3366,17 +3434,17 @@ def get_agent(self, agent_name: str, **kwargs: Any) -> _models1.KnowledgeAgent: return deserialized # type: ignore @distributed_trace - def list_agents(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeAgent"]: - """Lists all agents available for a search service. + def list_knowledge_bases(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeBase"]: + """Lists all knowledge bases available for a search service. - :return: An iterator like instance of KnowledgeAgent - :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] + :return: An iterator like instance of KnowledgeBase + :rtype: ~azure.core.paging.ItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[list[_models1.KnowledgeAgent]] = kwargs.pop("cls", None) + cls: ClsType[list[_models1.KnowledgeBase]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3389,7 +3457,7 @@ def list_agents(self, **kwargs: Any) -> ItemPaged["_models1.KnowledgeAgent"]: def prepare_request(next_link=None): if not next_link: - _request = build_search_index_list_agents_request( + _request = build_search_index_list_knowledge_bases_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -3425,7 +3493,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.KnowledgeAgent], deserialized.get("value", [])) + list_of_elem = _deserialize(list[_models1.KnowledgeBase], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return None, iter(list_of_elem) @@ -3441,7 +3509,10 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3449,65 +3520,64 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @overload - def create_agent( - self, knowledge_agent: _models1.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_knowledge_base( + self, knowledge_base: _models1.KnowledgeBase, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_agent( - self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_knowledge_base( + self, knowledge_base: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: JSON + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_agent( - self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. + def create_knowledge_base( + self, knowledge_base: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: IO[bytes] + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_agent( - self, knowledge_agent: Union[_models1.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any - ) -> _models1.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Is one of the following types: - KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + def create_knowledge_base( + self, knowledge_base: Union[_models1.KnowledgeBase, JSON, IO[bytes]], **kwargs: Any + ) -> _models1.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Is one of the following + types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3522,16 +3592,16 @@ def create_agent( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models1.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models1.KnowledgeBase] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_create_agent_request( + _request = build_search_index_create_knowledge_base_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -3557,13 +3627,16 @@ def create_agent( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models1.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models1.KnowledgeBase, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3648,7 +3721,7 @@ def _create_or_update_knowledge_source( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.KnowledgeSource] = kwargs.pop("cls", None) @@ -3689,7 +3762,10 @@ def _create_or_update_knowledge_source( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3765,7 +3841,10 @@ def _delete_knowledge_source( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3819,7 +3898,10 @@ def get_knowledge_source(self, source_name: str, **kwargs: Any) -> _models1.Know except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3908,7 +3990,10 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -4024,7 +4109,10 @@ def create_knowledge_source( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4082,7 +4170,10 @@ def get_service_statistics(self, **kwargs: Any) -> _models1.SearchServiceStatist except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4172,7 +4263,10 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -4270,7 +4364,7 @@ def _create_or_update_data_source_connection( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) @@ -4312,7 +4406,10 @@ def _create_or_update_data_source_connection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4388,7 +4485,10 @@ def _delete_data_source_connection( # pylint: disable=inconsistent-return-state if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -4445,7 +4545,10 @@ def get_data_source_connection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4510,7 +4613,10 @@ def _get_data_source_connections( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4642,7 +4748,10 @@ def create_data_source_connection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4698,7 +4807,10 @@ def reset_indexer(self, indexer_name: str, **kwargs: Any) -> None: # pylint: di if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -4747,7 +4859,10 @@ def resync(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disable=i if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -4914,7 +5029,10 @@ def reset_documents( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -4963,7 +5081,10 @@ def run_indexer(self, indexer_name: str, **kwargs: Any) -> None: # pylint: disa if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -5060,7 +5181,7 @@ def _create_or_update_indexer( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SearchIndexer] = kwargs.pop("cls", None) @@ -5103,7 +5224,10 @@ def _create_or_update_indexer( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5179,7 +5303,10 @@ def _delete_indexer( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -5233,7 +5360,10 @@ def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models1.SearchIndexe except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5296,7 +5426,10 @@ def _get_indexers(self, *, select: Optional[str] = None, **kwargs: Any) -> _mode except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5419,7 +5552,10 @@ def create_indexer( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5480,7 +5616,10 @@ def get_indexer_status(self, indexer_name: str, **kwargs: Any) -> _models1.Searc except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5585,7 +5724,7 @@ def _create_or_update_skillset( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models1.SearchIndexerSkillset] = kwargs.pop("cls", None) @@ -5628,7 +5767,10 @@ def _create_or_update_skillset( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5704,7 +5846,10 @@ def _delete_skillset( # pylint: disable=inconsistent-return-statements if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -5758,7 +5903,10 @@ def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models1.SearchInde except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5821,7 +5969,10 @@ def _get_skillsets(self, *, select: Optional[str] = None, **kwargs: Any) -> _mod except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -5948,7 +6099,10 @@ def create_skillset( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -6081,7 +6235,10 @@ def reset_skills( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models2.ErrorResponse, response) + error = _failsafe_deserialize( + _models2.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py index 07d2bd36f184..3fcd99daf989 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/_operations/_patch.py @@ -203,17 +203,17 @@ def delete_alias( ) @distributed_trace - def delete_agent( + def delete_knowledge_base( self, - agent: Union[str, _models.KnowledgeAgent], + knowledge_base: Union[str, _models.KnowledgeBase], *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: - """Deletes a knowledge agent. + """Deletes a knowledge base. - :param agent: The name of the agent to delete or a KnowledgeAgent object. Required. - :type agent: str or ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base: The name of the knowledge base to delete or a KnowledgeBase object. Required. + :type knowledge_base: str or ~azure.search.documents.indexes.models.KnowledgeBase :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None @@ -221,43 +221,43 @@ def delete_agent( :raises ~azure.core.exceptions.HttpResponseError: """ try: - name: str = agent.name # type: ignore - return self._delete_agent( - agent_name=name, + name: str = knowledge_base.name # type: ignore + return self._delete_knowledge_base( + knowledge_base_name=name, match_condition=match_condition, - etag=agent.e_tag, # type: ignore + etag=knowledge_base.e_tag, # type: ignore **kwargs, ) except AttributeError: - name = agent # type: ignore - return self._delete_agent( - agent_name=name, + name = knowledge_base # type: ignore + return self._delete_knowledge_base( + knowledge_base_name=name, **kwargs, ) @distributed_trace - def create_or_update_agent( + def create_or_update_knowledge_base( self, - agent: _models.KnowledgeAgent, + knowledge_base: _models.KnowledgeBase, *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + ) -> _models.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. - :param agent: The KnowledgeAgent object to create or update. Required. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base: The KnowledgeBase object to create or update. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ - return self._create_or_update_agent( - agent_name=agent.name, - agent=agent, + return self._create_or_update_knowledge_base( + knowledge_base_name=knowledge_base.name, + knowledge_base=knowledge_base, prefer="return=representation", - etag=agent.e_tag, + etag=knowledge_base.e_tag, match_condition=match_condition, **kwargs, ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py index aadec4d056c8..42192e8ec2e9 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_operations.py @@ -37,33 +37,33 @@ from ...._utils.utils import ClientMixinABC from ..._operations._operations import ( build_search_index_analyze_text_request, - build_search_index_create_agent_request, build_search_index_create_alias_request, build_search_index_create_index_request, + build_search_index_create_knowledge_base_request, build_search_index_create_knowledge_source_request, - build_search_index_create_or_update_agent_request, build_search_index_create_or_update_alias_request, build_search_index_create_or_update_index_request, + build_search_index_create_or_update_knowledge_base_request, build_search_index_create_or_update_knowledge_source_request, build_search_index_create_or_update_synonym_map_request, build_search_index_create_synonym_map_request, - build_search_index_delete_agent_request, build_search_index_delete_alias_request, build_search_index_delete_index_request, + build_search_index_delete_knowledge_base_request, build_search_index_delete_knowledge_source_request, build_search_index_delete_synonym_map_request, - build_search_index_get_agent_request, build_search_index_get_alias_request, build_search_index_get_index_request, build_search_index_get_index_statistics_request, + build_search_index_get_knowledge_base_request, build_search_index_get_knowledge_source_request, build_search_index_get_service_statistics_request, build_search_index_get_synonym_map_request, build_search_index_get_synonym_maps_request, - build_search_index_list_agents_request, build_search_index_list_aliases_request, build_search_index_list_index_stats_summary_request, build_search_index_list_indexes_request, + build_search_index_list_knowledge_bases_request, build_search_index_list_knowledge_sources_request, build_search_indexer_create_data_source_connection_request, build_search_indexer_create_indexer_request, @@ -175,7 +175,7 @@ async def _create_or_update_synonym_map( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SynonymMap] = kwargs.pop("cls", None) @@ -216,7 +216,10 @@ async def _create_or_update_synonym_map( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -292,7 +295,10 @@ async def _delete_synonym_map( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -346,7 +352,10 @@ async def get_synonym_map(self, synonym_map_name: str, **kwargs: Any) -> _models except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -411,7 +420,10 @@ async def _get_synonym_maps( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -534,7 +546,10 @@ async def create_synonym_map( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -642,7 +657,7 @@ async def _create_or_update_index( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SearchIndex] = kwargs.pop("cls", None) @@ -685,7 +700,10 @@ async def _create_or_update_index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -769,7 +787,10 @@ async def _delete_index( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -830,7 +851,10 @@ async def get_index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -925,7 +949,10 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1040,7 +1067,10 @@ async def create_index( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1109,7 +1139,10 @@ async def get_index_statistics( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1279,7 +1312,10 @@ async def analyze_text( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1369,7 +1405,7 @@ async def _create_or_update_alias( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SearchAlias] = kwargs.pop("cls", None) @@ -1410,7 +1446,10 @@ async def _create_or_update_alias( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1487,7 +1526,10 @@ async def _delete_alias( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -1541,7 +1583,10 @@ async def get_alias(self, alias_name: str, **kwargs: Any) -> _models2.SearchAlia except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1631,7 +1676,10 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1746,7 +1794,10 @@ async def create_alias( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -1760,64 +1811,63 @@ async def create_alias( return deserialized # type: ignore @overload - async def _create_or_update_agent( + async def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: _models2.KnowledgeAgent, + knowledge_base_name: str, + knowledge_base: _models2.KnowledgeBase, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: ... + ) -> _models2.KnowledgeBase: ... @overload - async def _create_or_update_agent( + async def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: JSON, + knowledge_base_name: str, + knowledge_base: JSON, *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: ... + ) -> _models2.KnowledgeBase: ... @overload - async def _create_or_update_agent( + async def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: IO[bytes], + knowledge_base_name: str, + knowledge_base: IO[bytes], *, content_type: str = "application/json", etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: ... + ) -> _models2.KnowledgeBase: ... @distributed_trace_async - async def _create_or_update_agent( + async def _create_or_update_knowledge_base( self, - agent_name: str, - knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], + knowledge_base_name: str, + knowledge_base: Union[_models2.KnowledgeBase, JSON, IO[bytes]], *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param knowledge_agent: The definition of the agent to create or update. Is one of the - following types: KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. + + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :param knowledge_base: The definition of the knowledge base to create or update. Is one of the + following types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1837,19 +1887,19 @@ async def _create_or_update_agent( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeBase] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_create_or_update_agent_request( - agent_name=agent_name, + _request = build_search_index_create_or_update_knowledge_base_request( + knowledge_base_name=knowledge_base_name, etag=etag, match_condition=match_condition, prefer=prefer, @@ -1871,20 +1921,23 @@ async def _create_or_update_agent( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: await response.read() # Load the body in memory and close the socket except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models2.KnowledgeBase, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1892,19 +1945,18 @@ async def _create_or_update_agent( return deserialized # type: ignore @distributed_trace_async - async def _delete_agent( + async def _delete_knowledge_base( self, - agent_name: str, + knowledge_base_name: str, *, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> None: - """Deletes a search alias and its associated mapping to an index. This operation is permanent, - with no recovery option. The mapped index is untouched by this operation. + """Deletes a knowledge base. - :param agent_name: The name of the agent. Required. - :type agent_name: str + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. :paramtype etag: str @@ -1933,8 +1985,8 @@ async def _delete_agent( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_search_index_delete_agent_request( - agent_name=agent_name, + _request = build_search_index_delete_knowledge_base_request( + knowledge_base_name=knowledge_base_name, etag=etag, match_condition=match_condition, api_version=self._config.api_version, @@ -1955,20 +2007,23 @@ async def _delete_agent( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get_agent(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeAgent: - """Retrieves an agent definition. + async def get_knowledge_base(self, knowledge_base_name: str, **kwargs: Any) -> _models2.KnowledgeBase: + """Retrieves a knowledge base definition. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base_name: The name of the knowledge base. Required. + :type knowledge_base_name: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1982,10 +2037,10 @@ async def get_agent(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeA _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeBase] = kwargs.pop("cls", None) - _request = build_search_index_get_agent_request( - agent_name=agent_name, + _request = build_search_index_get_knowledge_base_request( + knowledge_base_name=knowledge_base_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2009,13 +2064,16 @@ async def get_agent(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeA except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models2.KnowledgeBase, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2023,18 +2081,18 @@ async def get_agent(self, agent_name: str, **kwargs: Any) -> _models2.KnowledgeA return deserialized # type: ignore @distributed_trace - def list_agents(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeAgent"]: - """Lists all agents available for a search service. + def list_knowledge_bases(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeBase"]: + """Lists all knowledge bases available for a search service. - :return: An iterator like instance of KnowledgeAgent + :return: An iterator like instance of KnowledgeBase :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeAgent] + ~azure.core.async_paging.AsyncItemPaged[~azure.search.documents.indexes.models.KnowledgeBase] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[list[_models2.KnowledgeAgent]] = kwargs.pop("cls", None) + cls: ClsType[list[_models2.KnowledgeBase]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -2047,7 +2105,7 @@ def list_agents(self, **kwargs: Any) -> AsyncItemPaged["_models2.KnowledgeAgent" def prepare_request(next_link=None): if not next_link: - _request = build_search_index_list_agents_request( + _request = build_search_index_list_knowledge_bases_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -2083,7 +2141,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.KnowledgeAgent], deserialized.get("value", [])) + list_of_elem = _deserialize(list[_models2.KnowledgeBase], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return None, AsyncList(list_of_elem) @@ -2099,7 +2157,10 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2107,65 +2168,64 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @overload - async def create_agent( - self, knowledge_agent: _models2.KnowledgeAgent, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_knowledge_base( + self, knowledge_base: _models2.KnowledgeBase, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_agent( - self, knowledge_agent: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_knowledge_base( + self, knowledge_base: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: JSON + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_agent( - self, knowledge_agent: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. + async def create_knowledge_base( + self, knowledge_base: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. - :param knowledge_agent: The definition of the agent to create. Required. - :type knowledge_agent: IO[bytes] + :param knowledge_base: The definition of the knowledge base to create. Required. + :type knowledge_base: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_agent( - self, knowledge_agent: Union[_models2.KnowledgeAgent, JSON, IO[bytes]], **kwargs: Any - ) -> _models2.KnowledgeAgent: - """Creates a new agent. - - :param knowledge_agent: The definition of the agent to create. Is one of the following types: - KnowledgeAgent, JSON, IO[bytes] Required. - :type knowledge_agent: ~azure.search.documents.indexes.models.KnowledgeAgent or JSON or - IO[bytes] - :return: KnowledgeAgent. The KnowledgeAgent is compatible with MutableMapping - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + async def create_knowledge_base( + self, knowledge_base: Union[_models2.KnowledgeBase, JSON, IO[bytes]], **kwargs: Any + ) -> _models2.KnowledgeBase: + """Creates a new knowledge base. + + :param knowledge_base: The definition of the knowledge base to create. Is one of the following + types: KnowledgeBase, JSON, IO[bytes] Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase or JSON or IO[bytes] + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2180,16 +2240,16 @@ async def create_agent( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models2.KnowledgeAgent] = kwargs.pop("cls", None) + cls: ClsType[_models2.KnowledgeBase] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(knowledge_agent, (IOBase, bytes)): - _content = knowledge_agent + if isinstance(knowledge_base, (IOBase, bytes)): + _content = knowledge_base else: - _content = json.dumps(knowledge_agent, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(knowledge_base, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_search_index_create_agent_request( + _request = build_search_index_create_knowledge_base_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -2215,13 +2275,16 @@ async def create_agent( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models2.KnowledgeAgent, response.json()) + deserialized = _deserialize(_models2.KnowledgeBase, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2306,7 +2369,7 @@ async def _create_or_update_knowledge_source( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.KnowledgeSource] = kwargs.pop("cls", None) @@ -2347,7 +2410,10 @@ async def _create_or_update_knowledge_source( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2423,7 +2489,10 @@ async def _delete_knowledge_source( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -2477,7 +2546,10 @@ async def get_knowledge_source(self, source_name: str, **kwargs: Any) -> _models except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2567,7 +2639,10 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2683,7 +2758,10 @@ async def create_knowledge_source( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2741,7 +2819,10 @@ async def get_service_statistics(self, **kwargs: Any) -> _models2.SearchServiceS except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -2831,7 +2912,10 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2929,7 +3013,7 @@ async def _create_or_update_data_source_connection( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SearchIndexerDataSourceConnection] = kwargs.pop("cls", None) @@ -2971,7 +3055,10 @@ async def _create_or_update_data_source_connection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3047,7 +3134,10 @@ async def _delete_data_source_connection( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3104,7 +3194,10 @@ async def get_data_source_connection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3169,7 +3262,10 @@ async def _get_data_source_connections( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3301,7 +3397,10 @@ async def create_data_source_connection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3357,7 +3456,10 @@ async def reset_indexer(self, indexer_name: str, **kwargs: Any) -> None: if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3406,7 +3508,10 @@ async def resync(self, indexer_name: str, **kwargs: Any) -> None: if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3573,7 +3678,10 @@ async def reset_documents( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3622,7 +3730,10 @@ async def run_indexer(self, indexer_name: str, **kwargs: Any) -> None: if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3719,7 +3830,7 @@ async def _create_or_update_indexer( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SearchIndexer] = kwargs.pop("cls", None) @@ -3762,7 +3873,10 @@ async def _create_or_update_indexer( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3838,7 +3952,10 @@ async def _delete_indexer( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -3892,7 +4009,10 @@ async def get_indexer(self, indexer_name: str, **kwargs: Any) -> _models2.Search except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -3957,7 +4077,10 @@ async def _get_indexers( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4080,7 +4203,10 @@ async def create_indexer( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4141,7 +4267,10 @@ async def get_indexer_status(self, indexer_name: str, **kwargs: Any) -> _models2 except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4246,7 +4375,7 @@ async def _create_or_update_skillset( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - prefer: Literal["return=representation"] = kwargs.pop("prefer") + prefer: Literal["return=representation"] = kwargs.pop("prefer", _headers.pop("Prefer", "return=representation")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models2.SearchIndexerSkillset] = kwargs.pop("cls", None) @@ -4289,7 +4418,10 @@ async def _create_or_update_skillset( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4365,7 +4497,10 @@ async def _delete_skillset( if response.status_code not in [204, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: @@ -4419,7 +4554,10 @@ async def get_skillset(self, skillset_name: str, **kwargs: Any) -> _models2.Sear except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4484,7 +4622,10 @@ async def _get_skillsets( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4611,7 +4752,10 @@ async def create_skillset( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -4744,7 +4888,10 @@ async def reset_skills( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models3.ErrorResponse, response) + error = _failsafe_deserialize( + _models3.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if cls: diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py index a07aba8edbd4..89a8f5a00ab9 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/aio/_operations/_patch.py @@ -214,17 +214,17 @@ async def delete_alias( ) @distributed_trace_async - async def delete_agent( + async def delete_knowledge_base( self, - agent: Union[str, _models.KnowledgeAgent], + knowledge_base: Union[str, _models.KnowledgeBase], *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, ) -> None: - """Deletes a knowledge agent. + """Deletes a knowledge base. - :param agent: The name of the agent to delete or a KnowledgeAgent object. Required. - :type agent: str or ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base: The name of the knowledge base to delete or a KnowledgeBase object. Required. + :type knowledge_base: str or ~azure.search.documents.indexes.models.KnowledgeBase :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions :return: None @@ -232,44 +232,44 @@ async def delete_agent( :raises ~azure.core.exceptions.HttpResponseError: """ try: - name: str = agent.name # type: ignore - return await self._delete_agent( - agent_name=name, + name: str = knowledge_base.name # type: ignore + return await self._delete_knowledge_base( + knowledge_base_name=name, match_condition=match_condition, - etag=agent.e_tag, # type: ignore + etag=knowledge_base.e_tag, # type: ignore **kwargs, ) except AttributeError: - name = agent # type: ignore - return await self._delete_agent( - agent_name=name, + name = knowledge_base # type: ignore + return await self._delete_knowledge_base( + knowledge_base_name=name, **kwargs, ) @distributed_trace_async - async def create_or_update_agent( + async def create_or_update_knowledge_base( self, - agent: _models.KnowledgeAgent, + knowledge_base: _models.KnowledgeBase, *, match_condition: MatchConditions = MatchConditions.Unconditionally, **kwargs: Any, - ) -> _models.KnowledgeAgent: - """Creates a new agent or updates an agent if it already exists. + ) -> _models.KnowledgeBase: + """Creates a new knowledge base or updates a knowledge base if it already exists. - :param agent: The KnowledgeAgent object to create or update. Required. - :type agent: ~azure.search.documents.indexes.models.KnowledgeAgent + :param knowledge_base: The KnowledgeBase object to create or update. Required. + :type knowledge_base: ~azure.search.documents.indexes.models.KnowledgeBase :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: KnowledgeAgent - :rtype: ~azure.search.documents.indexes.models.KnowledgeAgent + :return: KnowledgeBase + :rtype: ~azure.search.documents.indexes.models.KnowledgeBase :raises ~azure.core.exceptions.HttpResponseError: """ - return await self._create_or_update_agent( - agent_name=agent.name, - agent=agent, + return await self._create_or_update_knowledge_base( + knowledge_base_name=knowledge_base.name, + knowledge_base=knowledge_base, prefer="return=representation", match_condition=match_condition, - etag=agent.e_tag, + etag=knowledge_base.e_tag, **kwargs, ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py index a4a3a9d430e6..65348a149df0 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py @@ -95,11 +95,9 @@ KeyPhraseExtractionSkill, KeywordMarkerTokenFilter, KeywordTokenizer, - KnowledgeAgent, - KnowledgeAgentAzureOpenAiModel, - KnowledgeAgentModel, - KnowledgeAgentOutputConfiguration, - KnowledgeAgentRequestLimits, + KnowledgeBase, + KnowledgeBaseAzureOpenAIModel, + KnowledgeBaseModel, KnowledgeSource, KnowledgeSourceReference, LanguageDetectionSkill, @@ -241,8 +239,7 @@ IndexerStatus, IndexingMode, KeyPhraseExtractionSkillLanguage, - KnowledgeAgentModelKind, - KnowledgeAgentOutputConfigurationModality, + KnowledgeBaseModelKind, KnowledgeSourceKind, LexicalAnalyzerName, LexicalNormalizerName, @@ -369,11 +366,9 @@ "KeyPhraseExtractionSkill", "KeywordMarkerTokenFilter", "KeywordTokenizer", - "KnowledgeAgent", - "KnowledgeAgentAzureOpenAiModel", - "KnowledgeAgentModel", - "KnowledgeAgentOutputConfiguration", - "KnowledgeAgentRequestLimits", + "KnowledgeBase", + "KnowledgeBaseAzureOpenAIModel", + "KnowledgeBaseModel", "KnowledgeSource", "KnowledgeSourceReference", "LanguageDetectionSkill", @@ -512,8 +507,7 @@ "IndexerStatus", "IndexingMode", "KeyPhraseExtractionSkillLanguage", - "KnowledgeAgentModelKind", - "KnowledgeAgentOutputConfigurationModality", + "KnowledgeBaseModelKind", "KnowledgeSourceKind", "LexicalAnalyzerName", "LexicalNormalizerName", diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py index 3a034616f35f..73639f767cfc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py @@ -545,22 +545,13 @@ class KeyPhraseExtractionSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumM """Swedish""" -class KnowledgeAgentModelKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class KnowledgeBaseModelKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The AI model to be used for query planning.""" AZURE_OPEN_AI = "azureOpenAI" """Use Azure Open AI models for query planning.""" -class KnowledgeAgentOutputConfigurationModality(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The output configuration for the agent.""" - - ANSWER_SYNTHESIS = "answerSynthesis" - """Synthesize an answer for the response payload.""" - EXTRACTIVE_DATA = "extractiveData" - """Return data from the knowledge sources directly without generative alteration.""" - - class KnowledgeSourceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The kind of the knowledge source.""" @@ -1089,13 +1080,13 @@ class OcrLineEnding(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Lines are separated by a single space character.""" CARRIAGE_RETURN = "carriageReturn" """Lines are separated by a carriage return (' -') character.""" + ') character.""" LINE_FEED = "lineFeed" """Lines are separated by a single line feed (' -') character.""" + ') character.""" CARRIAGE_RETURN_LINE_FEED = "carriageReturnLineFeed" """Lines are separated by a carriage return and a line feed (' -') character.""" + ') character.""" class OcrSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index a02289860450..1e53c3710e4e 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -13,7 +13,7 @@ from ..._utils.model_base import Model as _Model, rest_discriminator, rest_field from ._enums import ( - KnowledgeAgentModelKind, + KnowledgeBaseModelKind, KnowledgeSourceKind, VectorSearchAlgorithmKind, VectorSearchCompressionKind, @@ -22,6 +22,7 @@ if TYPE_CHECKING: from .. import models as _models + from ...knowledgebase import models as _knowledgebase_models3 class CognitiveServicesAccount(_Model): @@ -742,7 +743,7 @@ class AzureBlobKnowledgeSourceParameters(_Model): :vartype embedding_model: ~azure.search.documents.indexes.models.VectorSearchVectorizer :ivar chat_completion_model: Optional chat completion model for image verbalization or context extraction. - :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeAgentModel + :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeBaseModel :ivar ingestion_schedule: Optional schedule for data ingestion. :vartype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule :ivar created_resources: Resources created by the knowledge source. @@ -769,7 +770,7 @@ class AzureBlobKnowledgeSourceParameters(_Model): name="embeddingModel", visibility=["read", "create", "update", "delete", "query"] ) """Optional vectorizer configuration for vectorizing content.""" - chat_completion_model: Optional["_models.KnowledgeAgentModel"] = rest_field( + chat_completion_model: Optional["_models.KnowledgeBaseModel"] = rest_field( name="chatCompletionModel", visibility=["read", "create", "update", "delete", "query"] ) """Optional chat completion model for image verbalization or context extraction.""" @@ -793,7 +794,7 @@ def __init__( identity: Optional["_models.SearchIndexerDataIdentity"] = None, folder_path: Optional[str] = None, embedding_model: Optional["_models.VectorSearchVectorizer"] = None, - chat_completion_model: Optional["_models.KnowledgeAgentModel"] = None, + chat_completion_model: Optional["_models.KnowledgeBaseModel"] = None, ingestion_schedule: Optional["_models.IndexingSchedule"] = None, disable_image_verbalization: Optional[bool] = None, ) -> None: ... @@ -5313,73 +5314,86 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.odata_type = "#Microsoft.Azure.Search.KeywordTokenizerV2" # type: ignore -class KnowledgeAgent(_Model): - """Represents a knowledge agent definition. +class KnowledgeBase(_Model): + """Represents a knowledge base definition. - :ivar name: The name of the knowledge agent. Required. + :ivar name: The name of the knowledge base. Required. :vartype name: str - :ivar models: Contains configuration options on how to connect to AI models. Required. - :vartype models: list[~azure.search.documents.indexes.models.KnowledgeAgentModel] - :ivar knowledge_sources: Knowledge sources referenced by this agent. Required. + :ivar knowledge_sources: Knowledge sources referenced by this knowledge base. Required. :vartype knowledge_sources: list[~azure.search.documents.indexes.models.KnowledgeSourceReference] - :ivar output_configuration: Output configuration for the agent. - :vartype output_configuration: - ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfiguration - :ivar request_limits: Request limits for the agent. - :vartype request_limits: ~azure.search.documents.indexes.models.KnowledgeAgentRequestLimits - :ivar retrieval_instructions: Instructions considered by the knowledge agent when developing - query plan. - :vartype retrieval_instructions: str - :ivar e_tag: The ETag of the agent. + :ivar models: Contains configuration options on how to connect to AI models. + :vartype models: list[~azure.search.documents.indexes.models.KnowledgeBaseModel] + :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. + :vartype retrieval_reasoning_effort: + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffort + :ivar output_mode: The output mode for the knowledge base. Known values are: "extractiveData" + and "answerSynthesis". + :vartype output_mode: str or + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalOutputMode + :ivar e_tag: The ETag of the knowledge base. :vartype e_tag: str :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey - :ivar description: The description of the agent. + :ivar description: The description of the knowledge base. :vartype description: str + :ivar retrieval_instructions: Instructions considered by the knowledge base when developing + query plan. + :vartype retrieval_instructions: str + :ivar answer_instructions: Instructions considered by the knowledge base when generating + answers. + :vartype answer_instructions: str """ name: str = rest_field(visibility=["read"]) - """The name of the knowledge agent. Required.""" - models: list["_models.KnowledgeAgentModel"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Contains configuration options on how to connect to AI models. Required.""" + """The name of the knowledge base. Required.""" knowledge_sources: list["_models.KnowledgeSourceReference"] = rest_field( name="knowledgeSources", visibility=["read", "create", "update", "delete", "query"] ) - """Knowledge sources referenced by this agent. Required.""" - output_configuration: Optional["_models.KnowledgeAgentOutputConfiguration"] = rest_field( - name="outputConfiguration", visibility=["read", "create", "update", "delete", "query"] + """Knowledge sources referenced by this knowledge base. Required.""" + models: Optional[list["_models.KnowledgeBaseModel"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] ) - """Output configuration for the agent.""" - request_limits: Optional["_models.KnowledgeAgentRequestLimits"] = rest_field( - name="requestLimits", visibility=["read", "create", "update", "delete", "query"] + """Contains configuration options on how to connect to AI models.""" + retrieval_reasoning_effort: Optional["_knowledgebase_models3.KnowledgeRetrievalReasoningEffort"] = rest_field( + name="retrievalReasoningEffort", visibility=["read", "create", "update", "delete", "query"] ) - """Request limits for the agent.""" - retrieval_instructions: Optional[str] = rest_field( - name="retrievalInstructions", visibility=["read", "create", "update", "delete", "query"] + """The retrieval reasoning effort configuration.""" + output_mode: Optional[Union[str, "_knowledgebase_models3.KnowledgeRetrievalOutputMode"]] = rest_field( + name="outputMode", visibility=["read", "create", "update", "delete", "query"] ) - """Instructions considered by the knowledge agent when developing query plan.""" + """The output mode for the knowledge base. Known values are: \"extractiveData\" and + \"answerSynthesis\".""" e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) - """The ETag of the agent.""" + """The ETag of the knowledge base.""" encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] ) """A description of an encryption key that you create in Azure Key Vault.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The description of the agent.""" + """The description of the knowledge base.""" + retrieval_instructions: Optional[str] = rest_field( + name="retrievalInstructions", visibility=["read", "create", "update", "delete", "query"] + ) + """Instructions considered by the knowledge base when developing query plan.""" + answer_instructions: Optional[str] = rest_field( + name="answerInstructions", visibility=["read", "create", "update", "delete", "query"] + ) + """Instructions considered by the knowledge base when generating answers.""" @overload def __init__( self, *, - models: list["_models.KnowledgeAgentModel"], knowledge_sources: list["_models.KnowledgeSourceReference"], - output_configuration: Optional["_models.KnowledgeAgentOutputConfiguration"] = None, - request_limits: Optional["_models.KnowledgeAgentRequestLimits"] = None, - retrieval_instructions: Optional[str] = None, + models: Optional[list["_models.KnowledgeBaseModel"]] = None, + retrieval_reasoning_effort: Optional["_knowledgebase_models3.KnowledgeRetrievalReasoningEffort"] = None, + output_mode: Optional[Union[str, "_knowledgebase_models3.KnowledgeRetrievalOutputMode"]] = None, e_tag: Optional[str] = None, encryption_key: Optional["_models.SearchResourceEncryptionKey"] = None, description: Optional[str] = None, + retrieval_instructions: Optional[str] = None, + answer_instructions: Optional[str] = None, ) -> None: ... @overload @@ -5393,14 +5407,14 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class KnowledgeAgentModel(_Model): +class KnowledgeBaseModel(_Model): """Specifies the connection parameters for the model to use for query planning. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeAgentAzureOpenAiModel + KnowledgeBaseAzureOpenAIModel :ivar kind: The AI model to be used for query planning. Required. "azureOpenAI" - :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeAgentModelKind + :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeBaseModelKind """ __mapping__: dict[str, _Model] = {} @@ -5425,7 +5439,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class KnowledgeAgentAzureOpenAiModel(KnowledgeAgentModel, discriminator="azureOpenAI"): +class KnowledgeBaseAzureOpenAIModel(KnowledgeBaseModel, discriminator="azureOpenAI"): """Specifies the Azure OpenAI resource used to do query planning. :ivar kind: Required. Use Azure Open AI models for query planning. @@ -5434,7 +5448,7 @@ class KnowledgeAgentAzureOpenAiModel(KnowledgeAgentModel, discriminator="azureOp :vartype azure_open_ai_parameters: ~azure.search.documents.indexes.models.AzureOpenAiParameters """ - kind: Literal[KnowledgeAgentModelKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + kind: Literal[KnowledgeBaseModelKind.AZURE_OPEN_AI] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """Required. Use Azure Open AI models for query planning.""" azure_open_ai_parameters: "_models.AzureOpenAiParameters" = rest_field( name="azureOpenAIParameters", visibility=["read", "create", "update", "delete", "query"] @@ -5457,101 +5471,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.kind = KnowledgeAgentModelKind.AZURE_OPEN_AI # type: ignore - - -class KnowledgeAgentOutputConfiguration(_Model): - """Output configuration for knowledge agent. - - :ivar modality: The output configuration for the agent. Known values are: "answerSynthesis" and - "extractiveData". - :vartype modality: str or - ~azure.search.documents.indexes.models.KnowledgeAgentOutputConfigurationModality - :ivar answer_instructions: Instructions considered by the knowledge agent when generating - answers. - :vartype answer_instructions: str - :ivar attempt_fast_path: Indicates whether the agent should attempt to issue the most recent - chat message as a direct query to the knowledge sources, bypassing the model calls. - :vartype attempt_fast_path: bool - :ivar include_activity: Indicates retrieval results should include activity information. - :vartype include_activity: bool - """ - - modality: Optional[Union[str, "_models.KnowledgeAgentOutputConfigurationModality"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output configuration for the agent. Known values are: \"answerSynthesis\" and - \"extractiveData\".""" - answer_instructions: Optional[str] = rest_field( - name="answerInstructions", visibility=["read", "create", "update", "delete", "query"] - ) - """Instructions considered by the knowledge agent when generating answers.""" - attempt_fast_path: Optional[bool] = rest_field( - name="attemptFastPath", visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates whether the agent should attempt to issue the most recent chat message as a direct - query to the knowledge sources, bypassing the model calls.""" - include_activity: Optional[bool] = rest_field( - name="includeActivity", visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates retrieval results should include activity information.""" - - @overload - def __init__( - self, - *, - modality: Optional[Union[str, "_models.KnowledgeAgentOutputConfigurationModality"]] = None, - answer_instructions: Optional[str] = None, - attempt_fast_path: Optional[bool] = None, - include_activity: Optional[bool] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class KnowledgeAgentRequestLimits(_Model): - """Guardrails to limit how much resources are utilized for a single agent retrieval request. - - :ivar max_runtime_in_seconds: The maximum runtime in seconds. - :vartype max_runtime_in_seconds: int - :ivar max_output_size: Limits the maximum size of the content in the output. - :vartype max_output_size: int - """ - - max_runtime_in_seconds: Optional[int] = rest_field( - name="maxRuntimeInSeconds", visibility=["read", "create", "update", "delete", "query"] - ) - """The maximum runtime in seconds.""" - max_output_size: Optional[int] = rest_field( - name="maxOutputSize", visibility=["read", "create", "update", "delete", "query"] - ) - """Limits the maximum size of the content in the output.""" - - @overload - def __init__( - self, - *, - max_runtime_in_seconds: Optional[int] = None, - max_output_size: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + self.kind = KnowledgeBaseModelKind.AZURE_OPEN_AI # type: ignore class KnowledgeSourceReference(_Model): @@ -5559,59 +5479,16 @@ class KnowledgeSourceReference(_Model): :ivar name: The name of the knowledge source. Required. :vartype name: str - :ivar include_references: Indicates whether references should be included for data retrieved - from this source. - :vartype include_references: bool - :ivar include_reference_source_data: Indicates whether references should include the structured - data obtained during retrieval in their payload. - :vartype include_reference_source_data: bool - :ivar always_query_source: Indicates that this knowledge source should bypass source selection - and always be queried at retrieval time. - :vartype always_query_source: bool - :ivar max_sub_queries: The maximum number of queries that can be issued at a time when - retrieving data from this source. - :vartype max_sub_queries: int - :ivar reranker_threshold: The reranker threshold all retrieved documents must meet to be - included in the response. - :vartype reranker_threshold: float """ name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The name of the knowledge source. Required.""" - include_references: Optional[bool] = rest_field( - name="includeReferences", visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates whether references should be included for data retrieved from this source.""" - include_reference_source_data: Optional[bool] = rest_field( - name="includeReferenceSourceData", visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates whether references should include the structured data obtained during retrieval in - their payload.""" - always_query_source: Optional[bool] = rest_field( - name="alwaysQuerySource", visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates that this knowledge source should bypass source selection and always be queried at - retrieval time.""" - max_sub_queries: Optional[int] = rest_field( - name="maxSubQueries", visibility=["read", "create", "update", "delete", "query"] - ) - """The maximum number of queries that can be issued at a time when retrieving data from this - source.""" - reranker_threshold: Optional[float] = rest_field( - name="rerankerThreshold", visibility=["read", "create", "update", "delete", "query"] - ) - """The reranker threshold all retrieved documents must meet to be included in the response.""" @overload def __init__( self, *, name: str, - include_references: Optional[bool] = None, - include_reference_source_data: Optional[bool] = None, - always_query_source: Optional[bool] = None, - max_sub_queries: Optional[int] = None, - reranker_threshold: Optional[float] = None, ) -> None: ... @overload @@ -8440,7 +8317,7 @@ def __setattr__(self, key: str, value: Any) -> None: if key in self.__flattened_items: if self.credentials is None: self.credentials = self._attr_to_rest_field["credentials"]._class_type() - setattr(self.properties, key, value) + setattr(self.credentials, key, value) else: super().__setattr__(key, value) @@ -9477,7 +9354,7 @@ def __setattr__(self, key: str, value: Any) -> None: if key in self.__flattened_items: if self.access_credentials is None: self.access_credentials = self._attr_to_rest_field["access_credentials"]._class_type() - setattr(self.properties, key, value) + setattr(self.access_credentials, key, value) else: super().__setattr__(key, value) From 54c8fc8b178f5f6e9cfaa0b4088670ffad912c94 Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Fri, 31 Oct 2025 11:54:04 -0700 Subject: [PATCH 38/40] update --- .../search/documents/_operations/_patch.py | 8 +- .../azure/search/documents/_patch.py | 371 ++++++++++++++++- .../documents/aio/_operations/_patch.py | 8 +- .../azure/search/documents/aio/_patch.py | 374 +++++++++++++++++- .../azure/search/documents/models/_patch.py | 61 ++- 5 files changed, 806 insertions(+), 16 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py index ef895010c1d8..ddc57055012e 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_patch.py @@ -448,7 +448,7 @@ def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models :dedent: 4 :caption: Upload new documents to an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_upload_actions(documents) result = self.index_documents(batch, **kwargs) @@ -476,7 +476,7 @@ def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models :dedent: 4 :caption: Delete documents from an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_delete_actions(documents) result = self.index_documents(batch, **kwargs) @@ -504,7 +504,7 @@ def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_models. :dedent: 4 :caption: Merge documents in an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_merge_actions(documents) result = self.index_documents(batch, **kwargs) @@ -531,7 +531,7 @@ def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) -> Lis :dedent: 4 :caption: Merge or upload documents to an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_merge_or_upload_actions(documents) result = self.index_documents(batch, **kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index 722b424cb1fb..ddecfef13b84 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -7,13 +7,33 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Union +from typing import Any, Union, List, Dict, Optional, cast from enum import Enum +import time +import threading + from azure.core import CaseInsensitiveEnumMeta from azure.core.credentials import AzureKeyCredential, TokenCredential +from azure.core.tracing.decorator import distributed_trace +from azure.core.exceptions import ServiceResponseTimeoutError +from azure.core.pipeline.policies import AzureKeyCredentialPolicy, BearerTokenCredentialPolicy + from ._client import SearchClient as _SearchClient from ._operations._patch import SearchItemPaged -from .models._patch import RequestEntityTooLargeError +from .models._patch import RequestEntityTooLargeError, IndexDocumentsBatch +from .models import IndexAction, IndexingResult +from .indexes import SearchIndexClient +from ._version import VERSION as SDK_MONIKER + + +def is_retryable_status_code(status_code: int) -> bool: + """Check if a status code is retryable. + + :param int status_code: The status code to check + :return: True if the status code is retryable, False otherwise + :rtype: bool + """ + return status_code in (409, 422, 503) class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -45,9 +65,356 @@ def __init__( super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) +class SearchIndexingBufferedSender: + """A buffered sender for document indexing actions. + + :param endpoint: The URL endpoint of an Azure search service + :type endpoint: str + :param index_name: The name of the index to connect to + :type index_name: str + :param credential: A credential to authorize search client requests + :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential + :keyword bool auto_flush: Whether to automatically flush the batch. Default is True. + :keyword int auto_flush_interval: How many max seconds between 2 flushes. This only takes effect + when auto_flush is on. Default to 60 seconds. + :keyword int initial_batch_action_count: The initial number of actions to group into a batch when + tuning the behavior of the sender. The default value is 512. + :keyword int max_retries_per_action: The number of times to retry a failed document. The default value is 3. + :keyword callable on_new: If it is set, the client will call corresponding methods when there + is a new IndexAction added. This may be called from main thread or a worker thread. + :keyword callable on_progress: If it is set, the client will call corresponding methods when there + is a IndexAction succeeds. This may be called from main thread or a worker thread. + :keyword callable on_error: If it is set, the client will call corresponding methods when there + is a IndexAction fails. This may be called from main thread or a worker thread. + :keyword callable on_remove: If it is set, the client will call corresponding methods when there + is a IndexAction removed from the queue (succeeds or fails). This may be called from main + thread or a worker thread. + :keyword str api_version: The Search API version to use for requests. + :keyword str audience: Sets the Audience to use for authentication with Microsoft Entra ID. The + audience is not considered when using a shared key. If audience is not provided, the public cloud audience + will be assumed. + """ + + _ODATA_ACCEPT: str = "application/json;odata.metadata=none" + _DEFAULT_AUTO_FLUSH_INTERVAL = 60 + _DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512 + _DEFAULT_MAX_RETRIES = 3 + + def __init__( + self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any + ) -> None: + self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) + self._auto_flush = kwargs.pop("auto_flush", True) + self._batch_action_count = kwargs.pop("initial_batch_action_count", self._DEFAULT_INITIAL_BATCH_ACTION_COUNT) + self._auto_flush_interval = kwargs.pop("auto_flush_interval", self._DEFAULT_AUTO_FLUSH_INTERVAL) + if self._auto_flush_interval <= 0: + raise ValueError("auto_flush_interval must be a positive number.") + self._max_retries_per_action = kwargs.pop("max_retries_per_action", self._DEFAULT_MAX_RETRIES) + self._endpoint = endpoint + self._index_name = index_name + self._index_key: Optional[str] = None + self._credential = credential + self._on_new = kwargs.pop("on_new", None) + self._on_progress = kwargs.pop("on_progress", None) + self._on_error = kwargs.pop("on_error", None) + self._on_remove = kwargs.pop("on_remove", None) + self._retry_counter: Dict[str, int] = {} + + self._index_documents_batch = IndexDocumentsBatch() + audience = kwargs.pop("audience", None) + + # Create the search client based on credential type + if isinstance(credential, AzureKeyCredential): + self._aad = False + self._client = _SearchClient( + endpoint=endpoint, + index_name=index_name, + credential=credential, + api_version=self._api_version, + **kwargs + ) + else: + self._aad = True + self._client = _SearchClient( + endpoint=endpoint, + index_name=index_name, + credential=credential, + api_version=self._api_version, + **kwargs + ) + self._reset_timer() + + def _cleanup(self, flush: bool = True) -> None: + """Clean up the client. + + :param bool flush: Flush the actions queue before shutdown the client. Default to True. + """ + if flush: + self.flush() + if self._auto_flush: + self._timer.cancel() + + def __repr__(self) -> str: + return "".format( + repr(self._endpoint), repr(self._index_name) + )[:1024] + + @property + def actions(self) -> List[IndexAction]: + """The list of currently index actions in queue to index. + + :rtype: list[IndexAction] + """ + return self._index_documents_batch.actions if self._index_documents_batch.actions else [] + + @distributed_trace + def close(self, **kwargs) -> None: # pylint: disable=unused-argument + """Close the session. + + :return: None + :rtype: None + """ + self._cleanup(flush=True) + return self._client.close() + + @distributed_trace + def flush(self, timeout: int = 86400, **kwargs: Any) -> bool: # pylint:disable=unused-argument + """Flush the batch. + + :param int timeout: Time out setting. Default is 86400s (one day) + :return: True if there are errors. Else False + :rtype: bool + :raises ~azure.core.exceptions.ServiceResponseTimeoutError: + """ + has_error = False + begin_time = int(time.time()) + while len(self.actions) > 0: + now = int(time.time()) + remaining = timeout - (now - begin_time) + if remaining < 0: + if self._on_error: + actions = self._index_documents_batch.dequeue_actions() + for action in actions: + self._on_error(action) + raise ServiceResponseTimeoutError("Service response time out") + result = self._process(timeout=remaining, raise_error=False) + if result: + has_error = True + return has_error + + def _process(self, timeout: int = 86400, **kwargs) -> bool: + raise_error = kwargs.pop("raise_error", True) + actions = self._index_documents_batch.dequeue_actions() + has_error = False + if not self._index_key: + try: + credential = cast(Union[AzureKeyCredential, TokenCredential], self._credential) + client = SearchIndexClient(self._endpoint, credential) + index_result = client.get_index(self._index_name) + if index_result: + for field in index_result.fields: + if field.key: + self._index_key = field.name + break + except Exception: # pylint: disable=broad-except + pass + + self._reset_timer() + + try: + results = self._index_documents_actions(actions=actions, timeout=timeout) + for result in results: + try: + assert self._index_key is not None # Hint for mypy + action = next( + x + for x in actions + if x.additional_properties and x.additional_properties.get(self._index_key) == result.key + ) + if result.succeeded: + self._callback_succeed(action) + elif is_retryable_status_code(result.status_code): + self._retry_action(action) + has_error = True + else: + self._callback_fail(action) + has_error = True + except StopIteration: + pass + return has_error + except Exception: # pylint: disable=broad-except + for action in actions: + self._retry_action(action) + if raise_error: + raise + return True + return has_error + + def _process_if_needed(self) -> bool: + """Check if processing is needed and process if necessary. + + :return: True if process had errors, False otherwise + :rtype: bool + """ + if not self._auto_flush: + return False + + if len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) < self._batch_action_count: + return False + + return self._process(raise_error=False) + + def _reset_timer(self): + # pylint: disable=access-member-before-definition + try: + self._timer.cancel() + except AttributeError: + pass + self._timer = threading.Timer(self._auto_flush_interval, self._process) + if self._auto_flush: + self._timer.start() + + @distributed_trace + def upload_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument + """Queue upload documents actions. + + :param documents: A list of documents to upload. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_upload_actions(documents) + self._callback_new(actions) + self._process_if_needed() + + @distributed_trace + def delete_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument + """Queue delete documents actions + + :param documents: A list of documents to delete. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_delete_actions(documents) + self._callback_new(actions) + self._process_if_needed() + + @distributed_trace + def merge_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument + """Queue merge documents actions + + :param documents: A list of documents to merge. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_merge_actions(documents) + self._callback_new(actions) + self._process_if_needed() + + @distributed_trace + def merge_or_upload_documents(self, documents: List[Dict], **kwargs) -> None: + # pylint: disable=unused-argument + """Queue merge documents or upload documents actions + + :param documents: A list of documents to merge or upload. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_merge_or_upload_actions(documents) + self._callback_new(actions) + self._process_if_needed() + + @distributed_trace + def index_documents(self, batch: IndexDocumentsBatch, **kwargs) -> List[IndexingResult]: + """Specify a document operations to perform as a batch. + + :param batch: A batch of document operations to perform. + :type batch: IndexDocumentsBatch + :return: Indexing result of each action in the batch. + :rtype: list[IndexingResult] + :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. + """ + return self._index_documents_actions(actions=batch.actions if batch.actions else [], **kwargs) + + def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List[IndexingResult]: + error_map = {413: RequestEntityTooLargeError} + + timeout = kwargs.pop("timeout", 86400) + begin_time = int(time.time()) + + batch = IndexDocumentsBatch(actions=actions) + try: + batch_response = self._client.index_documents(batch=batch, **kwargs) + return cast(List[IndexingResult], batch_response) + except RequestEntityTooLargeError as ex: + if len(actions) == 1: + raise + pos = round(len(actions) / 2) + if pos < self._batch_action_count: + self._index_documents_batch.enqueue_actions(actions) + now = int(time.time()) + remaining = timeout - (now - begin_time) + if remaining < 0: + raise ServiceResponseTimeoutError("Service response time out") from ex + batch_response_first_half = self._index_documents_actions( + actions=actions[:pos], timeout=remaining, **kwargs + ) + result_first_half = list(batch_response_first_half) if batch_response_first_half else [] + + now = int(time.time()) + remaining = timeout - (now - begin_time) + if remaining < 0: + raise ServiceResponseTimeoutError("Service response time out") from ex + batch_response_second_half = self._index_documents_actions( + actions=actions[pos:], timeout=remaining, **kwargs + ) + result_second_half = list(batch_response_second_half) if batch_response_second_half else [] + + result_first_half.extend(result_second_half) + return result_first_half + + def __enter__(self) -> "SearchIndexingBufferedSender": + self._client.__enter__() # pylint:disable=no-member + return self + + def __exit__(self, *args) -> None: + self.close() + self._client.__exit__(*args) + + def _retry_action(self, action: IndexAction) -> None: + if not self._index_key: + self._callback_fail(action) + return + key = cast(str, action.additional_properties.get(self._index_key) if action.additional_properties else "") + counter = self._retry_counter.get(key) + if not counter: + # first time that fails + self._retry_counter[key] = 1 + self._index_documents_batch.enqueue_actions(action) + elif counter < self._max_retries_per_action - 1: + # not reach retry limit yet + self._retry_counter[key] = counter + 1 + self._index_documents_batch.enqueue_actions(action) + else: + self._callback_fail(action) + + def _callback_succeed(self, action: IndexAction) -> None: + if self._on_remove: + self._on_remove(action) + if self._on_progress: + self._on_progress(action) + + def _callback_fail(self, action: IndexAction) -> None: + if self._on_remove: + self._on_remove(action) + if self._on_error: + self._on_error(action) + + def _callback_new(self, actions: List[IndexAction]) -> None: + if self._on_new: + for action in actions: + self._on_new(action) + + __all__: list[str] = [ "SearchClient", "SearchItemPaged", + "SearchIndexingBufferedSender", "ApiVersion", "DEFAULT_VERSION", "RequestEntityTooLargeError", diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py index 408543fb5cde..d027f1c6199a 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_patch.py @@ -253,7 +253,7 @@ async def upload_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ :dedent: 4 :caption: Upload new documents to an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_upload_actions(documents) result = await self.index_documents(batch, **kwargs) @@ -281,7 +281,7 @@ async def delete_documents(self, documents: List[Dict], **kwargs: Any) -> List[_ :dedent: 4 :caption: Delete documents from an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_delete_actions(documents) result = await self.index_documents(batch, **kwargs) @@ -309,7 +309,7 @@ async def merge_documents(self, documents: List[Dict], **kwargs: Any) -> List[_m :dedent: 4 :caption: Merge documents in an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_merge_actions(documents) result = await self.index_documents(batch, **kwargs) @@ -336,7 +336,7 @@ async def merge_or_upload_documents(self, documents: List[Dict], **kwargs: Any) :dedent: 4 :caption: Merge or upload documents to an index """ - batch = _models.IndexDocumentsBatch(actions=[]) + batch = _models.IndexDocumentsBatch() batch.add_merge_or_upload_actions(documents) result = await self.index_documents(batch, **kwargs) diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index 313397192a0f..8261e5340772 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -7,11 +7,21 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Union +from typing import Any, Union, List, Dict, Optional, cast +import asyncio + from azure.core.credentials import AzureKeyCredential from azure.core.credentials_async import AsyncTokenCredential +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.exceptions import ServiceResponseTimeoutError + from ._client import SearchClient as _SearchClient from ._operations._patch import AsyncSearchItemPaged +from ..models._patch import RequestEntityTooLargeError, IndexDocumentsBatch +from ..models import IndexAction, IndexingResult +from ..indexes.aio import SearchIndexClient +from .._patch import ApiVersion, DEFAULT_VERSION, is_retryable_status_code +from .._version import VERSION as SDK_MONIKER class SearchClient(_SearchClient): @@ -37,9 +47,371 @@ def __init__( super().__init__(endpoint=endpoint, credential=credential, index_name=index_name, **kwargs) +class SearchIndexingBufferedSender: + """A buffered sender for document indexing actions (async version). + + :param endpoint: The URL endpoint of an Azure search service + :type endpoint: str + :param index_name: The name of the index to connect to + :type index_name: str + :param credential: A credential to authorize search client requests + :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential + :keyword bool auto_flush: Whether to automatically flush the batch. Default is True. + :keyword int auto_flush_interval: How many max seconds between 2 flushes. This only takes effect + when auto_flush is on. Default to 60 seconds. + :keyword int initial_batch_action_count: The initial number of actions to group into a batch when + tuning the behavior of the sender. The default value is 512. + :keyword int max_retries_per_action: The number of times to retry a failed document. The default value is 3. + :keyword callable on_new: If it is set, the client will call corresponding methods when there + is a new IndexAction added. + :keyword callable on_progress: If it is set, the client will call corresponding methods when there + is a IndexAction succeeds. + :keyword callable on_error: If it is set, the client will call corresponding methods when there + is a IndexAction fails. + :keyword callable on_remove: If it is set, the client will call corresponding methods when there + is a IndexAction removed from the queue (succeeds or fails). + :keyword str api_version: The Search API version to use for requests. + :keyword str audience: Sets the Audience to use for authentication with Microsoft Entra ID. + """ + + _ODATA_ACCEPT: str = "application/json;odata.metadata=none" + _DEFAULT_AUTO_FLUSH_INTERVAL = 60 + _DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512 + _DEFAULT_MAX_RETRIES = 3 + + def __init__( + self, + endpoint: str, + index_name: str, + credential: Union[AzureKeyCredential, AsyncTokenCredential], + **kwargs: Any + ) -> None: + self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) + self._auto_flush = kwargs.pop("auto_flush", True) + self._batch_action_count = kwargs.pop("initial_batch_action_count", self._DEFAULT_INITIAL_BATCH_ACTION_COUNT) + self._auto_flush_interval = kwargs.pop("auto_flush_interval", self._DEFAULT_AUTO_FLUSH_INTERVAL) + if self._auto_flush_interval <= 0: + raise ValueError("auto_flush_interval must be a positive number.") + self._max_retries_per_action = kwargs.pop("max_retries_per_action", self._DEFAULT_MAX_RETRIES) + self._endpoint = endpoint + self._index_name = index_name + self._index_key: Optional[str] = None + self._credential = credential + self._on_new = kwargs.pop("on_new", None) + self._on_progress = kwargs.pop("on_progress", None) + self._on_error = kwargs.pop("on_error", None) + self._on_remove = kwargs.pop("on_remove", None) + self._retry_counter: Dict[str, int] = {} + + self._index_documents_batch = IndexDocumentsBatch() + + # Create the search client + self._client = _SearchClient( + endpoint=endpoint, + index_name=index_name, + credential=credential, + api_version=self._api_version, + **kwargs + ) + self._auto_flush_task: Optional[asyncio.Task] = None + if self._auto_flush: + self._schedule_auto_flush() + + def _schedule_auto_flush(self) -> None: + """Schedule the auto flush task.""" + if self._auto_flush_task and not self._auto_flush_task.done(): + self._auto_flush_task.cancel() + + async def auto_flush_worker(): + await asyncio.sleep(self._auto_flush_interval) + await self._process() + + try: + loop = asyncio.get_event_loop() + self._auto_flush_task = loop.create_task(auto_flush_worker()) + except RuntimeError: + # If no event loop is running, we'll schedule when processing happens + self._auto_flush_task = None + + async def _cleanup(self, flush: bool = True) -> None: + """Clean up the client. + + :param bool flush: Flush the actions queue before shutdown the client. Default to True. + """ + if flush: + await self.flush() + if self._auto_flush_task and not self._auto_flush_task.done(): + self._auto_flush_task.cancel() + + def __repr__(self) -> str: + return "".format( + repr(self._endpoint), repr(self._index_name) + )[:1024] + + @property + def actions(self) -> List[IndexAction]: + """The list of currently index actions in queue to index. + + :rtype: list[IndexAction] + """ + return self._index_documents_batch.actions if self._index_documents_batch.actions else [] + + @distributed_trace_async + async def close(self, **kwargs) -> None: # pylint: disable=unused-argument + """Close the session. + + :return: None + :rtype: None + """ + await self._cleanup(flush=True) + await self._client.close() + + @distributed_trace_async + async def flush(self, timeout: int = 86400, **kwargs: Any) -> bool: # pylint:disable=unused-argument + """Flush the batch. + + :param int timeout: Time out setting. Default is 86400s (one day) + :return: True if there are errors. Else False + :rtype: bool + :raises ~azure.core.exceptions.ServiceResponseTimeoutError: + """ + has_error = False + begin_time = asyncio.get_event_loop().time() + while len(self.actions) > 0: + now = asyncio.get_event_loop().time() + remaining = timeout - (now - begin_time) + if remaining < 0: + if self._on_error: + actions = self._index_documents_batch.dequeue_actions() + for action in actions: + if asyncio.iscoroutinefunction(self._on_error): + await self._on_error(action) + else: + self._on_error(action) + raise ServiceResponseTimeoutError("Service response time out") + result = await self._process(timeout=remaining, raise_error=False) + if result: + has_error = True + return has_error + + async def _process(self, timeout: int = 86400, **kwargs) -> bool: + raise_error = kwargs.pop("raise_error", True) + actions = self._index_documents_batch.dequeue_actions() + has_error = False + + if not self._index_key: + try: + credential = cast(Union[AzureKeyCredential, AsyncTokenCredential], self._credential) + client = SearchIndexClient(self._endpoint, credential) + index_result = await client.get_index(self._index_name) + if index_result: + for field in index_result.fields: + if field.key: + self._index_key = field.name + break + await client.close() + except Exception: # pylint: disable=broad-except + pass + + self._schedule_auto_flush() + + try: + results = await self._index_documents_actions(actions=actions, timeout=timeout) + for result in results: + try: + assert self._index_key is not None # Hint for mypy + action = next( + x + for x in actions + if x.additional_properties and x.additional_properties.get(self._index_key) == result.key + ) + if result.succeeded: + await self._callback_succeed(action) + elif is_retryable_status_code(result.status_code): + self._retry_action(action) + has_error = True + else: + await self._callback_fail(action) + has_error = True + except StopIteration: + pass + return has_error + except Exception: # pylint: disable=broad-except + for action in actions: + self._retry_action(action) + if raise_error: + raise + return True + return has_error + + async def _process_if_needed(self) -> bool: + """Check if processing is needed and process if necessary. + + :return: True if process had errors, False otherwise + :rtype: bool + """ + if not self._auto_flush: + return False + + if len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) < self._batch_action_count: + return False + + return await self._process(raise_error=False) + + @distributed_trace_async + async def upload_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument + """Queue upload documents actions. + + :param documents: A list of documents to upload. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_upload_actions(documents) + await self._callback_new(actions) + await self._process_if_needed() + + @distributed_trace_async + async def delete_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument + """Queue delete documents actions + + :param documents: A list of documents to delete. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_delete_actions(documents) + await self._callback_new(actions) + await self._process_if_needed() + + @distributed_trace_async + async def merge_documents(self, documents: List[Dict], **kwargs) -> None: # pylint: disable=unused-argument + """Queue merge documents actions + + :param documents: A list of documents to merge. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_merge_actions(documents) + await self._callback_new(actions) + await self._process_if_needed() + + @distributed_trace_async + async def merge_or_upload_documents(self, documents: List[Dict], **kwargs) -> None: + # pylint: disable=unused-argument + """Queue merge documents or upload documents actions + + :param documents: A list of documents to merge or upload. + :type documents: list[dict] + """ + actions = self._index_documents_batch.add_merge_or_upload_actions(documents) + await self._callback_new(actions) + await self._process_if_needed() + + @distributed_trace_async + async def index_documents(self, batch: IndexDocumentsBatch, **kwargs) -> List[IndexingResult]: + """Specify a document operations to perform as a batch. + + :param batch: A batch of document operations to perform. + :type batch: IndexDocumentsBatch + :return: Indexing result of each action in the batch. + :rtype: list[IndexingResult] + :raises ~azure.search.documents.RequestEntityTooLargeError: The request is too large. + """ + return await self._index_documents_actions(actions=batch.actions if batch.actions else [], **kwargs) + + async def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List[IndexingResult]: + timeout = kwargs.pop("timeout", 86400) + begin_time = asyncio.get_event_loop().time() + + batch = IndexDocumentsBatch(actions=actions) + try: + batch_response = await self._client.index_documents(batch=batch, **kwargs) + return cast(List[IndexingResult], batch_response) + except RequestEntityTooLargeError as ex: + if len(actions) == 1: + raise + pos = round(len(actions) / 2) + if pos < self._batch_action_count: + self._index_documents_batch.enqueue_actions(actions) + now = asyncio.get_event_loop().time() + remaining = timeout - (now - begin_time) + if remaining < 0: + raise ServiceResponseTimeoutError("Service response time out") from ex + batch_response_first_half = await self._index_documents_actions( + actions=actions[:pos], timeout=remaining, **kwargs + ) + result_first_half = list(batch_response_first_half) if batch_response_first_half else [] + + now = asyncio.get_event_loop().time() + remaining = timeout - (now - begin_time) + if remaining < 0: + raise ServiceResponseTimeoutError("Service response time out") from ex + batch_response_second_half = await self._index_documents_actions( + actions=actions[pos:], timeout=remaining, **kwargs + ) + result_second_half = list(batch_response_second_half) if batch_response_second_half else [] + + result_first_half.extend(result_second_half) + return result_first_half + + async def __aenter__(self) -> "SearchIndexingBufferedSender": + await self._client.__aenter__() + return self + + async def __aexit__(self, *args) -> None: + await self.close() + await self._client.__aexit__(*args) + + def _retry_action(self, action: IndexAction) -> None: + if not self._index_key: + asyncio.create_task(self._callback_fail(action)) + return + key = cast(str, action.additional_properties.get(self._index_key) if action.additional_properties else "") + counter = self._retry_counter.get(key) + if not counter: + # first time that fails + self._retry_counter[key] = 1 + self._index_documents_batch.enqueue_actions(action) + elif counter < self._max_retries_per_action - 1: + # not reach retry limit yet + self._retry_counter[key] = counter + 1 + self._index_documents_batch.enqueue_actions(action) + else: + asyncio.create_task(self._callback_fail(action)) + + async def _callback_succeed(self, action: IndexAction) -> None: + if self._on_remove: + if asyncio.iscoroutinefunction(self._on_remove): + await self._on_remove(action) + else: + self._on_remove(action) + if self._on_progress: + if asyncio.iscoroutinefunction(self._on_progress): + await self._on_progress(action) + else: + self._on_progress(action) + + async def _callback_fail(self, action: IndexAction) -> None: + if self._on_remove: + if asyncio.iscoroutinefunction(self._on_remove): + await self._on_remove(action) + else: + self._on_remove(action) + if self._on_error: + if asyncio.iscoroutinefunction(self._on_error): + await self._on_error(action) + else: + self._on_error(action) + + async def _callback_new(self, actions: List[IndexAction]) -> None: + if self._on_new: + for action in actions: + if asyncio.iscoroutinefunction(self._on_new): + await self._on_new(action) + else: + self._on_new(action) + + __all__: list[str] = [ "SearchClient", "AsyncSearchItemPaged", + "SearchIndexingBufferedSender", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py index cbac73e992ac..0e5993a7c492 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py @@ -7,7 +7,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Dict, List +from typing import Any, Dict, List, Union from azure.core.exceptions import HttpResponseError from ._models import IndexDocumentsBatch as IndexDocumentsBatchGenerated @@ -22,7 +22,11 @@ class RequestEntityTooLargeError(HttpResponseError): class IndexDocumentsBatch(IndexDocumentsBatchGenerated): """Contains a batch of document write actions to send to the index.""" - def add_upload_actions(self, documents: List[Dict[str, Any]]) -> None: + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._actions_queue: List[IndexAction] = [] + + def add_upload_actions(self, documents: List[Dict[str, Any]]) -> List[IndexAction]: """Add upload actions for documents. An upload action is similar to an "upsert" where the document will be @@ -31,36 +35,46 @@ def add_upload_actions(self, documents: List[Dict[str, Any]]) -> None: :param documents: A list of documents to upload. :type documents: list[dict[str, Any]] + :return: The list of actions added + :rtype: list[~azure.search.documents.models.IndexAction] """ if not hasattr(self, "actions") or self.actions is None: self.actions = [] + actions = [] for doc in documents: # Create a mapping that includes both the action type and document fields action_dict = {"@search.action": IndexActionType.UPLOAD} action_dict.update(doc) action = IndexAction(action_dict) self.actions.append(action) + actions.append(action) + return actions - def add_delete_actions(self, documents: List[Dict[str, Any]]) -> None: + def add_delete_actions(self, documents: List[Dict[str, Any]]) -> List[IndexAction]: """Add delete actions for documents. Delete removes the specified documents from the index. :param documents: A list of documents to delete. :type documents: list[dict[str, Any]] + :return: The list of actions added + :rtype: list[~azure.search.documents.models.IndexAction] """ if not hasattr(self, "actions") or self.actions is None: self.actions = [] + actions = [] for doc in documents: # Create a mapping that includes both the action type and document fields action_dict = {"@search.action": IndexActionType.DELETE} action_dict.update(doc) action = IndexAction(action_dict) self.actions.append(action) + actions.append(action) + return actions - def add_merge_actions(self, documents: List[Dict[str, Any]]) -> None: + def add_merge_actions(self, documents: List[Dict[str, Any]]) -> List[IndexAction]: """Add merge actions for documents. Merge updates an existing document with the specified fields. If the document @@ -69,18 +83,23 @@ def add_merge_actions(self, documents: List[Dict[str, Any]]) -> None: :param documents: A list of documents to merge. :type documents: list[dict[str, Any]] + :return: The list of actions added + :rtype: list[~azure.search.documents.models.IndexAction] """ if not hasattr(self, "actions") or self.actions is None: self.actions = [] + actions = [] for doc in documents: # Create a mapping that includes both the action type and document fields action_dict = {"@search.action": IndexActionType.MERGE} action_dict.update(doc) action = IndexAction(action_dict) self.actions.append(action) + actions.append(action) + return actions - def add_merge_or_upload_actions(self, documents: List[Dict[str, Any]]) -> None: + def add_merge_or_upload_actions(self, documents: List[Dict[str, Any]]) -> List[IndexAction]: """Add merge or upload actions for documents. Merge or upload behaves like merge if a document with the given key already @@ -89,16 +108,48 @@ def add_merge_or_upload_actions(self, documents: List[Dict[str, Any]]) -> None: :param documents: A list of documents to merge or upload. :type documents: list[dict[str, Any]] + :return: The list of actions added + :rtype: list[~azure.search.documents.models.IndexAction] """ if not hasattr(self, "actions") or self.actions is None: self.actions = [] + actions = [] for doc in documents: # Create a mapping that includes both the action type and document fields action_dict = {"@search.action": IndexActionType.MERGE_OR_UPLOAD} action_dict.update(doc) action = IndexAction(action_dict) self.actions.append(action) + actions.append(action) + return actions + + def dequeue_actions(self) -> List[IndexAction]: + """Get and remove the actions from the batch. + + :return: The actions that were dequeued + :rtype: list[~azure.search.documents.models.IndexAction] + """ + if not hasattr(self, "actions") or self.actions is None: + return [] + + actions = self.actions + self.actions = [] + return actions + + def enqueue_actions(self, actions: Union[IndexAction, List[IndexAction]]) -> None: + """Add actions back to the batch. + + :param actions: The action(s) to enqueue + :type actions: ~azure.search.documents.models.IndexAction or list[~azure.search.documents.models.IndexAction] + """ + if not hasattr(self, "actions") or self.actions is None: + self.actions = [] + + if isinstance(actions, list): + self.actions.extend(actions) + else: + self.actions.append(actions) __all__: list[str] = [ From 8e3727643f5bc288e14809210e53e21a9b36748e Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Mon, 17 Nov 2025 10:28:11 -0800 Subject: [PATCH 39/40] updates --- .../azure/search/documents/_patch.py | 31 ++--- .../azure/search/documents/aio/_patch.py | 35 +++-- .../documents/indexes/models/__init__.py | 8 ++ .../search/documents/indexes/models/_enums.py | 16 +++ .../documents/indexes/models/_models.py | 120 +++++++++++++++++- .../documents/knowledgebase/models/_models.py | 42 ++++-- .../azure/search/documents/models/_patch.py | 8 +- 7 files changed, 206 insertions(+), 54 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_patch.py index ddecfef13b84..cc2eeec86028 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_patch.py @@ -28,7 +28,7 @@ def is_retryable_status_code(status_code: int) -> bool: """Check if a status code is retryable. - + :param int status_code: The status code to check :return: True if the status code is retryable, False otherwise :rtype: bool @@ -119,28 +119,20 @@ def __init__( self._on_error = kwargs.pop("on_error", None) self._on_remove = kwargs.pop("on_remove", None) self._retry_counter: Dict[str, int] = {} - + self._index_documents_batch = IndexDocumentsBatch() audience = kwargs.pop("audience", None) - + # Create the search client based on credential type if isinstance(credential, AzureKeyCredential): self._aad = False self._client = _SearchClient( - endpoint=endpoint, - index_name=index_name, - credential=credential, - api_version=self._api_version, - **kwargs + endpoint=endpoint, index_name=index_name, credential=credential, api_version=self._api_version, **kwargs ) else: self._aad = True self._client = _SearchClient( - endpoint=endpoint, - index_name=index_name, - credential=credential, - api_version=self._api_version, - **kwargs + endpoint=endpoint, index_name=index_name, credential=credential, api_version=self._api_version, **kwargs ) self._reset_timer() @@ -252,14 +244,17 @@ def _process(self, timeout: int = 86400, **kwargs) -> bool: def _process_if_needed(self) -> bool: """Check if processing is needed and process if necessary. - + :return: True if process had errors, False otherwise :rtype: bool """ if not self._auto_flush: return False - if len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) < self._batch_action_count: + if ( + len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) + < self._batch_action_count + ): return False return self._process(raise_error=False) @@ -336,7 +331,7 @@ def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List timeout = kwargs.pop("timeout", 86400) begin_time = int(time.time()) - + batch = IndexDocumentsBatch(actions=actions) try: batch_response = self._client.index_documents(batch=batch, **kwargs) @@ -355,7 +350,7 @@ def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List actions=actions[:pos], timeout=remaining, **kwargs ) result_first_half = list(batch_response_first_half) if batch_response_first_half else [] - + now = int(time.time()) remaining = timeout - (now - begin_time) if remaining < 0: @@ -364,7 +359,7 @@ def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List actions=actions[pos:], timeout=remaining, **kwargs ) result_second_half = list(batch_response_second_half) if batch_response_second_half else [] - + result_first_half.extend(result_second_half) return result_first_half diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py index 8261e5340772..a8a1e7c2b0da 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_patch.py @@ -80,11 +80,7 @@ class SearchIndexingBufferedSender: _DEFAULT_MAX_RETRIES = 3 def __init__( - self, - endpoint: str, - index_name: str, - credential: Union[AzureKeyCredential, AsyncTokenCredential], - **kwargs: Any + self, endpoint: str, index_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any ) -> None: self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) self._auto_flush = kwargs.pop("auto_flush", True) @@ -102,16 +98,12 @@ def __init__( self._on_error = kwargs.pop("on_error", None) self._on_remove = kwargs.pop("on_remove", None) self._retry_counter: Dict[str, int] = {} - + self._index_documents_batch = IndexDocumentsBatch() - + # Create the search client self._client = _SearchClient( - endpoint=endpoint, - index_name=index_name, - credential=credential, - api_version=self._api_version, - **kwargs + endpoint=endpoint, index_name=index_name, credential=credential, api_version=self._api_version, **kwargs ) self._auto_flush_task: Optional[asyncio.Task] = None if self._auto_flush: @@ -121,11 +113,11 @@ def _schedule_auto_flush(self) -> None: """Schedule the auto flush task.""" if self._auto_flush_task and not self._auto_flush_task.done(): self._auto_flush_task.cancel() - + async def auto_flush_worker(): await asyncio.sleep(self._auto_flush_interval) await self._process() - + try: loop = asyncio.get_event_loop() self._auto_flush_task = loop.create_task(auto_flush_worker()) @@ -198,7 +190,7 @@ async def _process(self, timeout: int = 86400, **kwargs) -> bool: raise_error = kwargs.pop("raise_error", True) actions = self._index_documents_batch.dequeue_actions() has_error = False - + if not self._index_key: try: credential = cast(Union[AzureKeyCredential, AsyncTokenCredential], self._credential) @@ -246,14 +238,17 @@ async def _process(self, timeout: int = 86400, **kwargs) -> bool: async def _process_if_needed(self) -> bool: """Check if processing is needed and process if necessary. - + :return: True if process had errors, False otherwise :rtype: bool """ if not self._auto_flush: return False - if len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) < self._batch_action_count: + if ( + len(self._index_documents_batch.actions if self._index_documents_batch.actions else []) + < self._batch_action_count + ): return False return await self._process(raise_error=False) @@ -318,7 +313,7 @@ async def index_documents(self, batch: IndexDocumentsBatch, **kwargs) -> List[In async def _index_documents_actions(self, actions: List[IndexAction], **kwargs) -> List[IndexingResult]: timeout = kwargs.pop("timeout", 86400) begin_time = asyncio.get_event_loop().time() - + batch = IndexDocumentsBatch(actions=actions) try: batch_response = await self._client.index_documents(batch=batch, **kwargs) @@ -337,7 +332,7 @@ async def _index_documents_actions(self, actions: List[IndexAction], **kwargs) - actions=actions[:pos], timeout=remaining, **kwargs ) result_first_half = list(batch_response_first_half) if batch_response_first_half else [] - + now = asyncio.get_event_loop().time() remaining = timeout - (now - begin_time) if remaining < 0: @@ -346,7 +341,7 @@ async def _index_documents_actions(self, actions: List[IndexAction], **kwargs) - actions=actions[pos:], timeout=remaining, **kwargs ) result_second_half = list(batch_response_second_half) if batch_response_second_half else [] - + result_first_half.extend(result_second_half) return result_first_half diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py index 65348a149df0..289c11c189fc 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/__init__.py @@ -48,6 +48,8 @@ CognitiveServicesAccountKey, CommonGramTokenFilter, ConditionalSkill, + ContentUnderstandingSkill, + ContentUnderstandingSkillChunkingProperties, CorsOptions, CreatedResources, CustomAnalyzer, @@ -219,6 +221,8 @@ ChatCompletionExtraParametersBehavior, ChatCompletionResponseFormatType, CjkBigramTokenFilterScripts, + ContentUnderstandingSkillChunkingUnit, + ContentUnderstandingSkillExtractionOptions, CustomEntityLookupSkillLanguage, DocumentIntelligenceLayoutSkillChunkingUnit, DocumentIntelligenceLayoutSkillExtractionOptions, @@ -319,6 +323,8 @@ "CognitiveServicesAccountKey", "CommonGramTokenFilter", "ConditionalSkill", + "ContentUnderstandingSkill", + "ContentUnderstandingSkillChunkingProperties", "CorsOptions", "CreatedResources", "CustomAnalyzer", @@ -487,6 +493,8 @@ "ChatCompletionExtraParametersBehavior", "ChatCompletionResponseFormatType", "CjkBigramTokenFilterScripts", + "ContentUnderstandingSkillChunkingUnit", + "ContentUnderstandingSkillExtractionOptions", "CustomEntityLookupSkillLanguage", "DocumentIntelligenceLayoutSkillChunkingUnit", "DocumentIntelligenceLayoutSkillExtractionOptions", diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py index 73639f767cfc..e4a4a4bbc1d9 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py @@ -152,6 +152,22 @@ class CjkBigramTokenFilterScripts(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Ignore Hangul script when forming bigrams of CJK terms.""" +class ContentUnderstandingSkillChunkingUnit(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Controls the cardinality of the chunk unit. Default is 'characters'.""" + + CHARACTERS = "characters" + """Specifies chunk by characters.""" + + +class ContentUnderstandingSkillExtractionOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Controls the cardinality of the content extracted from the document by the skill.""" + + IMAGES = "images" + """Specify that image content should be extracted from the document.""" + LOCATION_METADATA = "locationMetadata" + """Specify that location metadata should be extracted from the document.""" + + class CustomEntityLookupSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The language codes supported for input text by CustomEntityLookupSkill.""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 1e53c3710e4e..6ed5df0469c6 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -894,8 +894,9 @@ class SearchIndexerSkill(_Model): CustomEntityLookupSkill, EntityRecognitionSkill, KeyPhraseExtractionSkill, LanguageDetectionSkill, MergeSkill, PIIDetectionSkill, SentimentSkill, SplitSkill, TextTranslationSkill, EntityLinkingSkill, EntityRecognitionSkillV3, SentimentSkillV3, - ConditionalSkill, DocumentExtractionSkill, DocumentIntelligenceLayoutSkill, ShaperSkill, - ImageAnalysisSkill, OcrSkill, VisionVectorizeSkill + ConditionalSkill, ContentUnderstandingSkill, DocumentExtractionSkill, + DocumentIntelligenceLayoutSkill, ShaperSkill, ImageAnalysisSkill, OcrSkill, + VisionVectorizeSkill :ivar odata_type: The discriminator for derived types. Required. Default value is None. :vartype odata_type: str @@ -2374,6 +2375,121 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.odata_type = "#Microsoft.Skills.Util.ConditionalSkill" # type: ignore +class ContentUnderstandingSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Util.ContentUnderstandingSkill"): + """A skill that leverages Azure AI Content Understanding to process and extract structured + insights from documents, enabling enriched, searchable content for enhanced document indexing + and retrieval. + + :ivar name: The name of the skill which uniquely identifies it within the skillset. A skill + with no name defined will be given a default name of its 1-based index in the skills array, + prefixed with the character '#'. + :vartype name: str + :ivar description: The description of the skill which describes the inputs, outputs, and usage + of the skill. + :vartype description: str + :ivar context: Represents the level at which operations take place, such as the document root + or document content (for example, /document or /document/content). The default is /document. + :vartype context: str + :ivar inputs: Inputs of the skills could be a column in the source data set, or the output of + an upstream skill. Required. + :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar outputs: The output of a skill is either a field in a search index, or a value that can + be consumed as an input by another skill. Required. + :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] + :ivar extraction_options: Controls the cardinality of the content extracted from the document + by the skill. + :vartype extraction_options: list[str or + ~azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions] + :ivar chunking_properties: Controls the cardinality for chunking the content. + :vartype chunking_properties: + ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties + :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is + "#Microsoft.Skills.Util.ContentUnderstandingSkill". + :vartype odata_type: str + """ + + extraction_options: Optional[list[Union[str, "_models.ContentUnderstandingSkillExtractionOptions"]]] = rest_field( + name="extractionOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality of the content extracted from the document by the skill.""" + chunking_properties: Optional["_models.ContentUnderstandingSkillChunkingProperties"] = rest_field( + name="chunkingProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls the cardinality for chunking the content.""" + odata_type: Literal["#Microsoft.Skills.Util.ContentUnderstandingSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """A URI fragment specifying the type of skill. Required. Default value is + \"#Microsoft.Skills.Util.ContentUnderstandingSkill\".""" + + @overload + def __init__( + self, + *, + inputs: list["_models.InputFieldMappingEntry"], + outputs: list["_models.OutputFieldMappingEntry"], + name: Optional[str] = None, + description: Optional[str] = None, + context: Optional[str] = None, + extraction_options: Optional[list[Union[str, "_models.ContentUnderstandingSkillExtractionOptions"]]] = None, + chunking_properties: Optional["_models.ContentUnderstandingSkillChunkingProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Util.ContentUnderstandingSkill" # type: ignore + + +class ContentUnderstandingSkillChunkingProperties(_Model): # pylint: disable=name-too-long + """Controls the cardinality for chunking the content. + + :ivar unit: The unit of the chunk. "characters" + :vartype unit: str or + ~azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit + :ivar maximum_length: The maximum chunk length in characters. Default is 500. + :vartype maximum_length: int + :ivar overlap_length: The length of overlap provided between two text chunks. Default is 0. + :vartype overlap_length: int + """ + + unit: Optional[Union[str, "_models.ContentUnderstandingSkillChunkingUnit"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The unit of the chunk. \"characters\"""" + maximum_length: Optional[int] = rest_field( + name="maximumLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum chunk length in characters. Default is 500.""" + overlap_length: Optional[int] = rest_field( + name="overlapLength", visibility=["read", "create", "update", "delete", "query"] + ) + """The length of overlap provided between two text chunks. Default is 0.""" + + @overload + def __init__( + self, + *, + unit: Optional[Union[str, "_models.ContentUnderstandingSkillChunkingUnit"]] = None, + maximum_length: Optional[int] = None, + overlap_length: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class CorsOptions(_Model): """Defines options to control Cross-Origin Resource Sharing (CORS) for an index. diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py index 52e7361e8888..34f74d089118 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py @@ -1407,20 +1407,40 @@ class RemoteSharePointKnowledgeSourceParams(KnowledgeSourceParams, discriminator :ivar kind: The discriminator value. Required. A knowledge source that reads data from remote SharePoint. :vartype kind: str or ~azure.search.documents.indexes.models.REMOTE_SHARE_POINT - :ivar filter_expression_add_on: A filter condition applied to the SharePoint data source. It - must be specified in the Keyword Query Language syntax. It will be combined as a conjunction - with the filter expression specified in the knowledge source definition. - :vartype filter_expression_add_on: str + :ivar filter_expression: Keyword Query Language (KQL) expression with queryable SharePoint + properties and attributes to scope the retrieval before the query runs. See documentation: + `https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference + `_. + :vartype filter_expression: str + :ivar resource_metadata: A list of metadata fields to be returned for each item in the + response. Only retrievable metadata properties can be included in this list. By default, no + metadata is returned. Optional. + :vartype resource_metadata: list[str] + :ivar container_type_id: Container ID for SharePoint Embedded connection. When this is null, it + will use SharePoint Online. + :vartype container_type_id: str """ kind: Literal[KnowledgeSourceKind.REMOTE_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The discriminator value. Required. A knowledge source that reads data from remote SharePoint.""" - filter_expression_add_on: Optional[str] = rest_field( - name="filterExpressionAddOn", visibility=["read", "create", "update", "delete", "query"] + filter_expression: Optional[str] = rest_field( + name="filterExpression", visibility=["read", "create", "update", "delete", "query"] ) - """A filter condition applied to the SharePoint data source. It must be specified in the Keyword - Query Language syntax. It will be combined as a conjunction with the filter expression - specified in the knowledge source definition.""" + """Keyword Query Language (KQL) expression with queryable SharePoint properties and attributes to + scope the retrieval before the query runs. See documentation: + `https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference + `_.""" + resource_metadata: Optional[list[str]] = rest_field( + name="resourceMetadata", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of metadata fields to be returned for each item in the response. Only retrievable + metadata properties can be included in this list. By default, no metadata is returned. + Optional.""" + container_type_id: Optional[str] = rest_field( + name="containerTypeId", visibility=["read", "create", "update", "delete", "query"] + ) + """Container ID for SharePoint Embedded connection. When this is null, it will use SharePoint + Online.""" @overload def __init__( @@ -1431,7 +1451,9 @@ def __init__( include_reference_source_data: Optional[bool] = None, always_query_source: Optional[bool] = None, reranker_threshold: Optional[float] = None, - filter_expression_add_on: Optional[str] = None, + filter_expression: Optional[str] = None, + resource_metadata: Optional[list[str]] = None, + container_type_id: Optional[str] = None, ) -> None: ... @overload diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py index 0e5993a7c492..e5895636caee 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_patch.py @@ -126,26 +126,26 @@ def add_merge_or_upload_actions(self, documents: List[Dict[str, Any]]) -> List[I def dequeue_actions(self) -> List[IndexAction]: """Get and remove the actions from the batch. - + :return: The actions that were dequeued :rtype: list[~azure.search.documents.models.IndexAction] """ if not hasattr(self, "actions") or self.actions is None: return [] - + actions = self.actions self.actions = [] return actions def enqueue_actions(self, actions: Union[IndexAction, List[IndexAction]]) -> None: """Add actions back to the batch. - + :param actions: The action(s) to enqueue :type actions: ~azure.search.documents.models.IndexAction or list[~azure.search.documents.models.IndexAction] """ if not hasattr(self, "actions") or self.actions is None: self.actions = [] - + if isinstance(actions, list): self.actions.extend(actions) else: From 21b68f8da275ea4485101d9c9d7656488dbd4ece Mon Sep 17 00:00:00 2001 From: Xiang Yan Date: Wed, 19 Nov 2025 12:34:31 -0800 Subject: [PATCH 40/40] updates --- .../documents/_operations/_operations.py | 6 +- .../documents/aio/_operations/_operations.py | 6 +- .../search/documents/indexes/models/_enums.py | 30 +- .../documents/indexes/models/_models.py | 672 ++++++++---------- .../knowledgebase/models/__init__.py | 2 - .../documents/knowledgebase/models/_enums.py | 4 +- .../documents/knowledgebase/models/_models.py | 315 +++----- .../azure/search/documents/models/_enums.py | 5 +- .../azure/search/documents/models/_models.py | 143 ++-- 9 files changed, 501 insertions(+), 682 deletions(-) diff --git a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py index f462aa29f982..aaa77a9fbd72 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_operations/_operations.py @@ -818,7 +818,7 @@ def _search_get( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 206]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -1033,7 +1033,7 @@ def _search_post( "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". Default value is None. :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct + :keyword query_speller: A value that specifies the type of the speller to use to spell-correct individual search query terms. Known values are: "none" and "lexicon". Default value is None. :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields @@ -1170,7 +1170,7 @@ def _search_post( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 206]: if _stream: try: response.read() # Load the body in memory and close the socket diff --git a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py index f2943145d805..6e4c11e42532 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py +++ b/sdk/search/azure-search-documents/azure/search/documents/aio/_operations/_operations.py @@ -373,7 +373,7 @@ async def _search_get( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 206]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -588,7 +588,7 @@ async def _search_post( "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". Default value is None. :paramtype query_language: str or ~azure.search.documents.models.QueryLanguage - :keyword query_speller: A value that specified the type of the speller to use to spell-correct + :keyword query_speller: A value that specifies the type of the speller to use to spell-correct individual search query terms. Known values are: "none" and "lexicon". Default value is None. :paramtype query_speller: str or ~azure.search.documents.models.QuerySpellerType :keyword select: The comma-separated list of fields to retrieve. If unspecified, all fields @@ -725,7 +725,7 @@ async def _search_post( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 206]: if _stream: try: await response.read() # Load the body in memory and close the socket diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py index e4a4a4bbc1d9..18bd966f7412 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_enums.py @@ -26,6 +26,8 @@ class AIFoundryModelCatalogName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Cohere-embed-v3-english""" COHERE_EMBED_V3_MULTILINGUAL = "Cohere-embed-v3-multilingual" """Cohere-embed-v3-multilingual""" + COHERE_EMBED_V4 = "Cohere-embed-v4" + """Cohere embed v4 model for generating embeddings from both text and images.""" class AzureOpenAIModelName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -37,6 +39,22 @@ class AzureOpenAIModelName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """TextEmbedding3Large model.""" TEXT_EMBEDDING3_SMALL = "text-embedding-3-small" """TextEmbedding3Small model.""" + GPT4_O = "gpt-4o" + """Gpt4o model.""" + GPT4_O_MINI = "gpt-4o-mini" + """Gpt4oMini model.""" + GPT41 = "gpt-4.1" + """Gpt41 model.""" + GPT41_MINI = "gpt-4.1-mini" + """Gpt41Mini model.""" + GPT41_NANO = "gpt-4.1-nano" + """Gpt41Nano model.""" + GPT5 = "gpt-5" + """Gpt5 model.""" + GPT5_MINI = "gpt-5-mini" + """Gpt5Mini model.""" + GPT5_NANO = "gpt-5-nano" + """Gpt5Nano model.""" class BlobIndexerDataToExtract(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -120,7 +138,7 @@ class CharFilterName(str, Enum, metaclass=CaseInsensitiveEnumMeta): class ChatCompletionExtraParametersBehavior(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies how 'extraParameters' should be handled by Azure AI Foundry. Defaults to 'error'.""" - PASS_THROUGH = "passThrough" + PASS_THROUGH = "pass-through" """Passes any extra parameters directly to the model.""" DROP = "drop" """Drops all extra parameters.""" @@ -1433,7 +1451,7 @@ class OcrSkillLanguage(str, Enum, metaclass=CaseInsensitiveEnumMeta): UZ = "uz" """Uzbek (Latin)""" VO = "vo" - """Volapük""" + """Volapük""" WAE = "wae" """Walser""" CY = "cy" @@ -1481,9 +1499,9 @@ class PhoneticEncoder(str, Enum, metaclass=CaseInsensitiveEnumMeta): NYSIIS = "nysiis" """Encodes a token into a NYSIIS value.""" KOELNER_PHONETIK = "koelnerPhonetik" - """Encodes a token using the Kölner Phonetik algorithm.""" + """Encodes a token using the Kölner Phonetik algorithm.""" HAASE_PHONETIK = "haasePhonetik" - """Encodes a token using the Haase refinement of the Kölner Phonetik algorithm.""" + """Encodes a token using the Haase refinement of the Kölner Phonetik algorithm.""" BEIDER_MORSE = "beiderMorse" """Encodes a token into a Beider-Morse value.""" @@ -1548,6 +1566,8 @@ class ScoringFunctionAggregation(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Boost scores by the maximum of all scoring function results.""" FIRST_MATCHING = "firstMatching" """Boost scores using the first applicable scoring function in the scoring profile.""" + PRODUCT = "product" + """Boost scores by the product of all scoring function results.""" class ScoringFunctionInterpolation(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -1622,6 +1642,8 @@ class SearchIndexerDataSourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Indicates an ADLS Gen2 datasource.""" ONE_LAKE = "onelake" """Indicates a Microsoft Fabric OneLake datasource.""" + SHARE_POINT = "sharepoint" + """Indicates a SharePoint datasource.""" class SearchIndexPermissionFilterOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py index 6ed5df0469c6..51b56504bb02 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/indexes/models/_models.py @@ -22,6 +22,7 @@ if TYPE_CHECKING: from .. import models as _models + from ......search import models as _search_models6 from ...knowledgebase import models as _knowledgebase_models3 @@ -314,38 +315,18 @@ class AnalyzedTokenInfo(_Model): :vartype position: int """ - token: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + token: str = rest_field(visibility=["read"]) """The token returned by the analyzer. Required.""" - start_offset: int = rest_field(name="startOffset", visibility=["read", "create", "update", "delete", "query"]) + start_offset: int = rest_field(name="startOffset", visibility=["read"]) """The index of the first character of the token in the input text. Required.""" - end_offset: int = rest_field(name="endOffset", visibility=["read", "create", "update", "delete", "query"]) + end_offset: int = rest_field(name="endOffset", visibility=["read"]) """The index of the last character of the token in the input text. Required.""" - position: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + position: int = rest_field(visibility=["read"]) """The position of the token in the input text relative to other tokens. The first token in the input text has position 0, the next has position 1, and so on. Depending on the analyzer used, some tokens might have the same position, for example if they are synonyms of each other. Required.""" - @overload - def __init__( - self, - *, - token: str, - start_offset: int, - end_offset: int, - position: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class AnalyzeResult(_Model): """The result of testing an analyzer on text. @@ -354,26 +335,9 @@ class AnalyzeResult(_Model): :vartype tokens: list[~azure.search.documents.indexes.models.AnalyzedTokenInfo] """ - tokens: list["_models.AnalyzedTokenInfo"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + tokens: list["_models.AnalyzedTokenInfo"] = rest_field(visibility=["read"]) """The list of tokens returned by the analyzer specified in the request. Required.""" - @overload - def __init__( - self, - *, - tokens: list["_models.AnalyzedTokenInfo"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class AnalyzeTextOptions(_Model): """Specifies some text and analysis components used to break that text into tokens. @@ -499,9 +463,10 @@ class TokenFilter(_Model): AsciiFoldingTokenFilter, CjkBigramTokenFilter, CommonGramTokenFilter, DictionaryDecompounderTokenFilter, EdgeNGramTokenFilter, ElisionTokenFilter, KeepTokenFilter, KeywordMarkerTokenFilter, LengthTokenFilter, LimitTokenFilter, NGramTokenFilter, - PatternCaptureTokenFilter, PatternReplaceTokenFilter, PhoneticTokenFilter, ShingleTokenFilter, - SnowballTokenFilter, StemmerOverrideTokenFilter, StemmerTokenFilter, StopwordsTokenFilter, - SynonymTokenFilter, TruncateTokenFilter, UniqueTokenFilter, WordDelimiterTokenFilter + NGramTokenFilterV2, PatternCaptureTokenFilter, PatternReplaceTokenFilter, PhoneticTokenFilter, + ShingleTokenFilter, SnowballTokenFilter, StemmerOverrideTokenFilter, StemmerTokenFilter, + StopwordsTokenFilter, SynonymTokenFilter, TruncateTokenFilter, UniqueTokenFilter, + WordDelimiterTokenFilter :ivar odata_type: The discriminator for derived types. Required. Default value is None. :vartype odata_type: str @@ -627,7 +592,8 @@ class KnowledgeSource(_Model): """Represents a knowledge source definition. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureBlobKnowledgeSource, SearchIndexKnowledgeSource + AzureBlobKnowledgeSource, IndexedOneLakeKnowledgeSource, IndexedSharePointKnowledgeSource, + RemoteSharePointKnowledgeSource, SearchIndexKnowledgeSource, WebKnowledgeSource :ivar name: The name of the knowledge source. Required. :vartype name: str @@ -636,31 +602,46 @@ class KnowledgeSource(_Model): :ivar kind: The type of the knowledge source. Required. Known values are: "searchIndex", "azureBlob", "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". :vartype kind: str or ~azure.search.documents.indexes.models.KnowledgeSourceKind - :ivar e_tag: The ETag of the agent. + :ivar e_tag: The ETag of the knowledge source. :vartype e_tag: str :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey """ __mapping__: dict[str, _Model] = {} - name: str = rest_field(visibility=["read"]) + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The name of the knowledge source. Required.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description.""" kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type of the knowledge source. Required. Known values are: \"searchIndex\", \"azureBlob\", \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" - e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) - """The ETag of the agent.""" + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the knowledge source.""" encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] ) - """A description of an encryption key that you create in Azure Key Vault.""" + """A description of an encryption key that you create in Azure Key Vault. This key is used to + provide an additional level of encryption-at-rest for your knowledge source definition when you + want full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted + your knowledge source definition, it will always remain encrypted. The search service will + ignore attempts to set this property to null. You can change this property as needed if you + want to rotate your encryption key; Your knowledge source definition will be unaffected. + Encryption with customer-managed keys is not available for free search services, and is only + available for paid services created on or after January 1, 2019.""" @overload def __init__( self, *, + name: str, kind: str, description: Optional[str] = None, e_tag: Optional[str] = None, @@ -685,9 +666,16 @@ class AzureBlobKnowledgeSource(KnowledgeSource, discriminator="azureBlob"): :vartype name: str :ivar description: Optional user-defined description. :vartype description: str - :ivar e_tag: The ETag of the agent. + :ivar e_tag: The ETag of the knowledge source. :vartype e_tag: str :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey :ivar kind: Required. A knowledge source that read and ingest data from Azure Blob Storage to a Search Index. @@ -709,6 +697,7 @@ class AzureBlobKnowledgeSource(KnowledgeSource, discriminator="azureBlob"): def __init__( self, *, + name: str, azure_blob_parameters: "_models.AzureBlobKnowledgeSourceParameters", description: Optional[str] = None, e_tag: Optional[str] = None, @@ -730,8 +719,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class AzureBlobKnowledgeSourceParameters(_Model): """Parameters for Azure Blob Storage knowledge source. - :ivar identity: An explicit identity to use for this knowledge source. - :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity :ivar connection_string: Key-based connection string or the ResourceId format if using a managed identity. Required. :vartype connection_string: str @@ -739,23 +726,15 @@ class AzureBlobKnowledgeSourceParameters(_Model): :vartype container_name: str :ivar folder_path: Optional folder path within the container. :vartype folder_path: str - :ivar embedding_model: Optional vectorizer configuration for vectorizing content. - :vartype embedding_model: ~azure.search.documents.indexes.models.VectorSearchVectorizer - :ivar chat_completion_model: Optional chat completion model for image verbalization or context - extraction. - :vartype chat_completion_model: ~azure.search.documents.indexes.models.KnowledgeBaseModel - :ivar ingestion_schedule: Optional schedule for data ingestion. - :vartype ingestion_schedule: ~azure.search.documents.indexes.models.IndexingSchedule + :ivar is_adls_gen2: Set to true if connecting to an ADLS Gen2 storage account. Default is + false. + :vartype is_adls_gen2: bool + :ivar ingestion_parameters: Consolidates all general ingestion settings. + :vartype ingestion_parameters: ~search.models.KnowledgeSourceIngestionParameters :ivar created_resources: Resources created by the knowledge source. :vartype created_resources: ~azure.search.documents.indexes.models.CreatedResources - :ivar disable_image_verbalization: Indicates whether image verbalization should be disabled. - :vartype disable_image_verbalization: bool """ - identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """An explicit identity to use for this knowledge source.""" connection_string: str = rest_field( name="connectionString", visibility=["read", "create", "update", "delete", "query"] ) @@ -766,24 +745,16 @@ class AzureBlobKnowledgeSourceParameters(_Model): name="folderPath", visibility=["read", "create", "update", "delete", "query"] ) """Optional folder path within the container.""" - embedding_model: Optional["_models.VectorSearchVectorizer"] = rest_field( - name="embeddingModel", visibility=["read", "create", "update", "delete", "query"] + is_adls_gen2: Optional[bool] = rest_field( + name="isADLSGen2", visibility=["read", "create", "update", "delete", "query"] ) - """Optional vectorizer configuration for vectorizing content.""" - chat_completion_model: Optional["_models.KnowledgeBaseModel"] = rest_field( - name="chatCompletionModel", visibility=["read", "create", "update", "delete", "query"] + """Set to true if connecting to an ADLS Gen2 storage account. Default is false.""" + ingestion_parameters: Optional["_search_models6.KnowledgeSourceIngestionParameters"] = rest_field( + name="ingestionParameters", visibility=["read", "create", "update", "delete", "query"] ) - """Optional chat completion model for image verbalization or context extraction.""" - ingestion_schedule: Optional["_models.IndexingSchedule"] = rest_field( - name="ingestionSchedule", visibility=["read", "create", "update", "delete", "query"] - ) - """Optional schedule for data ingestion.""" + """Consolidates all general ingestion settings.""" created_resources: Optional["_models.CreatedResources"] = rest_field(name="createdResources", visibility=["read"]) """Resources created by the knowledge source.""" - disable_image_verbalization: Optional[bool] = rest_field( - name="disableImageVerbalization", visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates whether image verbalization should be disabled.""" @overload def __init__( @@ -791,12 +762,9 @@ def __init__( *, connection_string: str, container_name: str, - identity: Optional["_models.SearchIndexerDataIdentity"] = None, folder_path: Optional[str] = None, - embedding_model: Optional["_models.VectorSearchVectorizer"] = None, - chat_completion_model: Optional["_models.KnowledgeBaseModel"] = None, - ingestion_schedule: Optional["_models.IndexingSchedule"] = None, - disable_image_verbalization: Optional[bool] = None, + is_adls_gen2: Optional[bool] = None, + ingestion_parameters: Optional["_search_models6.KnowledgeSourceIngestionParameters"] = None, ) -> None: ... @overload @@ -833,7 +801,7 @@ class AzureMachineLearningParameters(_Model): "OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32", "OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336", "Facebook-DinoV2-Image-Embeddings-ViT-Base", "Facebook-DinoV2-Image-Embeddings-ViT-Giant", - "Cohere-embed-v3-english", and "Cohere-embed-v3-multilingual". + "Cohere-embed-v3-english", "Cohere-embed-v3-multilingual", and "Cohere-embed-v4". :vartype model_name: str or ~azure.search.documents.indexes.models.AIFoundryModelCatalogName """ @@ -861,7 +829,7 @@ class AzureMachineLearningParameters(_Model): provided endpoint. Known values are: \"OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32\", \"OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336\", \"Facebook-DinoV2-Image-Embeddings-ViT-Base\", \"Facebook-DinoV2-Image-Embeddings-ViT-Giant\", - \"Cohere-embed-v3-english\", and \"Cohere-embed-v3-multilingual\".""" + \"Cohere-embed-v3-english\", \"Cohere-embed-v3-multilingual\", and \"Cohere-embed-v4\".""" @overload def __init__( @@ -1142,9 +1110,13 @@ class AzureOpenAIEmbeddingSkill(SearchIndexerSkill, discriminator="#Microsoft.Sk :ivar auth_identity: The user-assigned managed identity used for outbound connections. :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", and - "text-embedding-3-small". + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", + "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", + "gpt-5", "gpt-5-mini", and "gpt-5-nano". :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + :ivar authentication_method: The authentication method to use when connecting to the Azure + OpenAI resource. + :vartype authentication_method: str :ivar dimensions: The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. :vartype dimensions: int @@ -1171,8 +1143,13 @@ class AzureOpenAIEmbeddingSkill(SearchIndexerSkill, discriminator="#Microsoft.Sk name="modelName", visibility=["read", "create", "update", "delete", "query"] ) """The name of the embedding model that is deployed at the provided deploymentId path. Known - values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", and - \"text-embedding-3-small\".""" + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", \"text-embedding-3-small\", + \"gpt-4o\", \"gpt-4o-mini\", \"gpt-4.1\", \"gpt-4.1-mini\", \"gpt-4.1-nano\", \"gpt-5\", + \"gpt-5-mini\", and \"gpt-5-nano\".""" + authentication_method: Optional[str] = rest_field( + name="authenticationMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The authentication method to use when connecting to the Azure OpenAI resource.""" dimensions: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.""" @@ -1194,6 +1171,7 @@ def __init__( api_key: Optional[str] = None, auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + authentication_method: Optional[str] = None, dimensions: Optional[int] = None, ) -> None: ... @@ -1222,8 +1200,9 @@ class AzureOpenAiParameters(_Model): :ivar auth_identity: The user-assigned managed identity used for outbound connections. :vartype auth_identity: str :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", and - "text-embedding-3-small". + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", + "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", + "gpt-5", "gpt-5-mini", and "gpt-5-nano". :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName :ivar authentication_method: The authentication method to use when connecting to the Azure OpenAI resource. @@ -1244,8 +1223,9 @@ class AzureOpenAiParameters(_Model): name="modelName", visibility=["read", "create", "update", "delete", "query"] ) """The name of the embedding model that is deployed at the provided deploymentId path. Known - values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", and - \"text-embedding-3-small\".""" + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", \"text-embedding-3-small\", + \"gpt-4o\", \"gpt-4o-mini\", \"gpt-4.1\", \"gpt-4.1-mini\", \"gpt-4.1-nano\", \"gpt-5\", + \"gpt-5-mini\", and \"gpt-5-nano\".""" authentication_method: Optional[str] = rest_field( name="authenticationMethod", visibility=["read", "create", "update", "delete", "query"] ) @@ -1372,9 +1352,13 @@ class AzureOpenAIVectorizerParameters(_Model): :ivar auth_identity: The user-assigned managed identity used for outbound connections. :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity :ivar model_name: The name of the embedding model that is deployed at the provided deploymentId - path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", and - "text-embedding-3-small". + path. Known values are: "text-embedding-ada-002", "text-embedding-3-large", + "text-embedding-3-small", "gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", + "gpt-5", "gpt-5-mini", and "gpt-5-nano". :vartype model_name: str or ~azure.search.documents.indexes.models.AzureOpenAIModelName + :ivar authentication_method: The authentication method to use when connecting to the Azure + OpenAI resource. + :vartype authentication_method: str """ resource_url: Optional[str] = rest_field( @@ -1395,8 +1379,13 @@ class AzureOpenAIVectorizerParameters(_Model): name="modelName", visibility=["read", "create", "update", "delete", "query"] ) """The name of the embedding model that is deployed at the provided deploymentId path. Known - values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", and - \"text-embedding-3-small\".""" + values are: \"text-embedding-ada-002\", \"text-embedding-3-large\", \"text-embedding-3-small\", + \"gpt-4o\", \"gpt-4o-mini\", \"gpt-4.1\", \"gpt-4.1-mini\", \"gpt-4.1-nano\", \"gpt-5\", + \"gpt-5-mini\", and \"gpt-5-nano\".""" + authentication_method: Optional[str] = rest_field( + name="authenticationMethod", visibility=["read", "create", "update", "delete", "query"] + ) + """The authentication method to use when connecting to the Azure OpenAI resource.""" @overload def __init__( @@ -1407,6 +1396,7 @@ def __init__( api_key: Optional[str] = None, auth_identity: Optional["_models.SearchIndexerDataIdentity"] = None, model_name: Optional[Union[str, "_models.AzureOpenAIModelName"]] = None, + authentication_method: Optional[str] = None, ) -> None: ... @overload @@ -1429,16 +1419,6 @@ class VectorSearchCompression(_Model): :ivar compression_name: The name to associate with this particular configuration. Required. :vartype compression_name: str - :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated - using compressed vectors are obtained, they will be reranked again by recalculating the - full-precision similarity scores. This will improve recall at the expense of latency. - :vartype rerank_with_original_vectors: bool - :ivar default_oversampling: Default oversampling factor. Oversampling will internally request - more documents (specified by this multiplier) in the initial search. This increases the set of - results that will be reranked using recomputed similarity scores from full-precision vectors. - Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :vartype default_oversampling: float :ivar rescoring_options: Contains the options for rescoring. :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the @@ -1456,20 +1436,6 @@ class VectorSearchCompression(_Model): __mapping__: dict[str, _Model] = {} compression_name: str = rest_field(name="name", visibility=["read", "create", "update", "delete", "query"]) """The name to associate with this particular configuration. Required.""" - rerank_with_original_vectors: Optional[bool] = rest_field( - name="rerankWithOriginalVectors", visibility=["read", "create", "update", "delete", "query"] - ) - """If set to true, once the ordered set of results calculated using compressed vectors are - obtained, they will be reranked again by recalculating the full-precision similarity scores. - This will improve recall at the expense of latency.""" - default_oversampling: Optional[float] = rest_field( - name="defaultOversampling", visibility=["read", "create", "update", "delete", "query"] - ) - """Default oversampling factor. Oversampling will internally request more documents (specified by - this multiplier) in the initial search. This increases the set of results that will be reranked - using recomputed similarity scores from full-precision vectors. Minimum value is 1, meaning no - oversampling (1x). This parameter can only be set when rerankWithOriginalVectors is true. - Higher values improve recall at the expense of latency.""" rescoring_options: Optional["_models.RescoringOptions"] = rest_field( name="rescoringOptions", visibility=["read", "create", "update", "delete", "query"] ) @@ -1492,8 +1458,6 @@ def __init__( *, compression_name: str, kind: str, - rerank_with_original_vectors: Optional[bool] = None, - default_oversampling: Optional[float] = None, rescoring_options: Optional["_models.RescoringOptions"] = None, truncation_dimension: Optional[int] = None, ) -> None: ... @@ -1515,16 +1479,6 @@ class BinaryQuantizationCompression(VectorSearchCompression, discriminator="bina :ivar compression_name: The name to associate with this particular configuration. Required. :vartype compression_name: str - :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated - using compressed vectors are obtained, they will be reranked again by recalculating the - full-precision similarity scores. This will improve recall at the expense of latency. - :vartype rerank_with_original_vectors: bool - :ivar default_oversampling: Default oversampling factor. Oversampling will internally request - more documents (specified by this multiplier) in the initial search. This increases the set of - results that will be reranked using recomputed similarity scores from full-precision vectors. - Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :vartype default_oversampling: float :ivar rescoring_options: Contains the options for rescoring. :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the @@ -1554,8 +1508,6 @@ def __init__( self, *, compression_name: str, - rerank_with_original_vectors: Optional[bool] = None, - default_oversampling: Optional[float] = None, rescoring_options: Optional["_models.RescoringOptions"] = None, truncation_dimension: Optional[int] = None, ) -> None: ... @@ -1720,7 +1672,7 @@ class ChatCompletionCommonModelParameters(_Model): :vartype stop: list[str] """ - model_name: Optional[str] = rest_field(name="modelName", visibility=["read", "create", "update", "delete", "query"]) + model_name: Optional[str] = rest_field(name="model", visibility=["read", "create", "update", "delete", "query"]) """The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified.""" frequency_penalty: Optional[float] = rest_field( name="frequencyPenalty", visibility=["read", "create", "update", "delete", "query"] @@ -1815,7 +1767,7 @@ class ChatCompletionSchema(_Model): constraints for the model. :vartype properties: str :ivar required: An array of the property names that are required to be part of the model's - response. + response. All properties must be included for structured outputs. :vartype required: list[str] :ivar additional_properties: Controls whether it is allowable for an object to contain additional keys / values that were not defined in the JSON Schema. Default is false. @@ -1828,7 +1780,8 @@ class ChatCompletionSchema(_Model): """A JSON-formatted string that defines the output schema's properties and constraints for the model.""" required: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An array of the property names that are required to be part of the model's response.""" + """An array of the property names that are required to be part of the model's response. All + properties must be included for structured outputs.""" additional_properties: Optional[bool] = rest_field( name="additionalProperties", visibility=["read", "create", "update", "delete", "query"] ) @@ -1935,9 +1888,16 @@ class ChatCompletionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.C API. :vartype degree_of_parallelism: int :ivar auth_resource_id: Applies to custom skills that connect to external code in an Azure - function or some other application that provides the transformations. + function or some other application that provides the transformations. This value should be the + application ID created for the function or app when it was registered with Azure Active + Directory. When specified, the custom skill connects to the function or app using a managed ID + (either system or user-assigned) of the search service and the access token of the function or + app, using this value as the resource id for creating the scope of the access token. :vartype auth_resource_id: str - :ivar auth_identity: The user-assigned managed identity used for outbound connections. + :ivar auth_identity: The user-assigned managed identity used for outbound connections. If an + authResourceId is provided and it's not specified, the system-assigned managed identity is + used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. + If set to "none", the value of this property is cleared. :vartype auth_identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity :ivar api_key: API key for authenticating to the model. Both apiKey and authIdentity cannot be specified at the same time. @@ -1950,7 +1910,7 @@ class ChatCompletionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.C appended to the chat completions call. Follows Azure AI Foundry's extensibility pattern. :vartype extra_parameters: dict[str, any] :ivar extra_parameters_behavior: How extra parameters are handled by Azure AI Foundry. Default - is 'error'. Known values are: "passThrough", "drop", and "error". + is 'error'. Known values are: "pass-through", "drop", and "error". :vartype extra_parameters_behavior: str or ~azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior :ivar response_format: Determines how the LLM should format its response. Defaults to 'text' @@ -1983,11 +1943,18 @@ class ChatCompletionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.C name="authResourceId", visibility=["read", "create", "update", "delete", "query"] ) """Applies to custom skills that connect to external code in an Azure function or some other - application that provides the transformations.""" + application that provides the transformations. This value should be the application ID created + for the function or app when it was registered with Azure Active Directory. When specified, the + custom skill connects to the function or app using a managed ID (either system or + user-assigned) of the search service and the access token of the function or app, using this + value as the resource id for creating the scope of the access token.""" auth_identity: Optional["_models.SearchIndexerDataIdentity"] = rest_field( name="authIdentity", visibility=["read", "create", "update", "delete", "query"] ) - """The user-assigned managed identity used for outbound connections.""" + """The user-assigned managed identity used for outbound connections. If an authResourceId is + provided and it's not specified, the system-assigned managed identity is used. On updates to + the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", + the value of this property is cleared.""" api_key: Optional[str] = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) """API key for authenticating to the model. Both apiKey and authIdentity cannot be specified at the same time.""" @@ -2005,7 +1972,7 @@ class ChatCompletionSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.C name="extraParametersBehavior", visibility=["read", "create", "update", "delete", "query"] ) """How extra parameters are handled by Azure AI Foundry. Default is 'error'. Known values are: - \"passThrough\", \"drop\", and \"error\".""" + \"pass-through\", \"drop\", and \"error\".""" response_format: Optional["_models.ChatCompletionResponseFormat"] = rest_field( name="responseFormat", visibility=["read", "create", "update", "delete", "query"] ) @@ -3496,8 +3463,8 @@ class DocumentIntelligenceLayoutSkill( :ivar outputs: The output of a skill is either a field in a search index, or a value that can be consumed as an input by another skill. Required. :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] - :ivar output_format: Controls the cardinality of the output produced by the skill. Default is - 'oneToMany'. Known values are: "text" and "markdown". + :ivar output_format: Controls the output format. Default is 'markdown'. Known values are: + "text" and "markdown". :vartype output_format: str or ~azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat :ivar output_mode: Controls the cardinality of the output produced by the skill. Default is @@ -3523,8 +3490,7 @@ class DocumentIntelligenceLayoutSkill( output_format: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputFormat"]] = rest_field( name="outputFormat", visibility=["read", "create", "update", "delete", "query"] ) - """Controls the cardinality of the output produced by the skill. Default is 'oneToMany'. Known - values are: \"text\" and \"markdown\".""" + """Controls the output format. Default is 'markdown'. Known values are: \"text\" and \"markdown\".""" output_mode: Optional[Union[str, "_models.DocumentIntelligenceLayoutSkillOutputMode"]] = rest_field( name="outputMode", visibility=["read", "create", "update", "delete", "query"] ) @@ -4360,34 +4326,13 @@ class GetIndexStatisticsResult(_Model): :vartype vector_index_size: int """ - document_count: int = rest_field(name="documentCount", visibility=["read", "create", "update", "delete", "query"]) + document_count: int = rest_field(name="documentCount", visibility=["read"]) """The number of documents in the index. Required.""" - storage_size: int = rest_field(name="storageSize", visibility=["read", "create", "update", "delete", "query"]) + storage_size: int = rest_field(name="storageSize", visibility=["read"]) """The amount of storage in bytes consumed by the index. Required.""" - vector_index_size: int = rest_field( - name="vectorIndexSize", visibility=["read", "create", "update", "delete", "query"] - ) + vector_index_size: int = rest_field(name="vectorIndexSize", visibility=["read"]) """The amount of memory in bytes consumed by vectors in the index. Required.""" - @overload - def __init__( - self, - *, - document_count: int, - storage_size: int, - vector_index_size: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class HighWaterMarkChangeDetectionPolicy( DataChangeDetectionPolicy, discriminator="#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy" @@ -4722,9 +4667,7 @@ class IndexerExecutionResult(_Model): :vartype final_tracking_state: str """ - status: Union[str, "_models.IndexerExecutionStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) + status: Union[str, "_models.IndexerExecutionStatus"] = rest_field(visibility=["read"]) """The outcome of this indexer execution. Required. Known values are: \"transientFailure\", \"success\", \"inProgress\", and \"reset\".""" status_detail: Optional[Union[str, "_models.IndexerExecutionStatusDetail"]] = rest_field( @@ -4736,64 +4679,26 @@ class IndexerExecutionResult(_Model): \"indexingResetDocs\", and \"indexingResync\".""" current_state: Optional["_models.IndexerCurrentState"] = rest_field(name="currentState", visibility=["read"]) """All of the state that defines and dictates the indexer's current execution.""" - error_message: Optional[str] = rest_field( - name="errorMessage", visibility=["read", "create", "update", "delete", "query"] - ) + error_message: Optional[str] = rest_field(name="errorMessage", visibility=["read"]) """The error message indicating the top-level error, if any.""" - start_time: Optional[datetime.datetime] = rest_field( - name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) + start_time: Optional[datetime.datetime] = rest_field(name="startTime", visibility=["read"], format="rfc3339") """The start time of this indexer execution.""" - end_time: Optional[datetime.datetime] = rest_field( - name="endTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) + end_time: Optional[datetime.datetime] = rest_field(name="endTime", visibility=["read"], format="rfc3339") """The end time of this indexer execution, if the execution has already completed.""" - errors: list["_models.SearchIndexerError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + errors: list["_models.SearchIndexerError"] = rest_field(visibility=["read"]) """The item-level indexing errors. Required.""" - warnings: list["_models.SearchIndexerWarning"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) + warnings: list["_models.SearchIndexerWarning"] = rest_field(visibility=["read"]) """The item-level indexing warnings. Required.""" - item_count: int = rest_field(name="itemsProcessed", visibility=["read", "create", "update", "delete", "query"]) + item_count: int = rest_field(name="itemsProcessed", visibility=["read"]) """The number of items that were processed during this indexer execution. This includes both successfully processed items and items where indexing was attempted but failed. Required.""" - failed_item_count: int = rest_field(name="itemsFailed", visibility=["read", "create", "update", "delete", "query"]) + failed_item_count: int = rest_field(name="itemsFailed", visibility=["read"]) """The number of items that failed to be indexed during this indexer execution. Required.""" - initial_tracking_state: Optional[str] = rest_field( - name="initialTrackingState", visibility=["read", "create", "update", "delete", "query"] - ) + initial_tracking_state: Optional[str] = rest_field(name="initialTrackingState", visibility=["read"]) """Change tracking state with which an indexer execution started.""" - final_tracking_state: Optional[str] = rest_field( - name="finalTrackingState", visibility=["read", "create", "update", "delete", "query"] - ) + final_tracking_state: Optional[str] = rest_field(name="finalTrackingState", visibility=["read"]) """Change tracking state with which an indexer execution finished.""" - @overload - def __init__( - self, - *, - status: Union[str, "_models.IndexerExecutionStatus"], - errors: list["_models.SearchIndexerError"], - warnings: list["_models.SearchIndexerWarning"], - item_count: int, - failed_item_count: int, - error_message: Optional[str] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - initial_tracking_state: Optional[str] = None, - final_tracking_state: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class IndexerResyncBody(_Model): """Request body for resync indexer operation. @@ -5145,17 +5050,35 @@ class IndexStatisticsSummary(_Model): :ivar storage_size: The amount of storage in bytes consumed by the index. Required. :vartype storage_size: int :ivar vector_index_size: The amount of memory in bytes consumed by vectors in the index. + Required. :vartype vector_index_size: int """ - name: str = rest_field(visibility=["read"]) + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The name of the index. Required.""" document_count: int = rest_field(name="documentCount", visibility=["read"]) """The number of documents in the index. Required.""" storage_size: int = rest_field(name="storageSize", visibility=["read"]) """The amount of storage in bytes consumed by the index. Required.""" - vector_index_size: Optional[int] = rest_field(name="vectorIndexSize", visibility=["read"]) - """The amount of memory in bytes consumed by vectors in the index.""" + vector_index_size: int = rest_field(name="vectorIndexSize", visibility=["read"]) + """The amount of memory in bytes consumed by vectors in the index. Required.""" + + @overload + def __init__( + self, + *, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) class InputFieldMappingEntry(_Model): @@ -5461,7 +5384,7 @@ class KnowledgeBase(_Model): :vartype answer_instructions: str """ - name: str = rest_field(visibility=["read"]) + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The name of the knowledge base. Required.""" knowledge_sources: list["_models.KnowledgeSourceReference"] = rest_field( name="knowledgeSources", visibility=["read", "create", "update", "delete", "query"] @@ -5480,7 +5403,7 @@ class KnowledgeBase(_Model): ) """The output mode for the knowledge base. Known values are: \"extractiveData\" and \"answerSynthesis\".""" - e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) """The ETag of the knowledge base.""" encryption_key: Optional["_models.SearchResourceEncryptionKey"] = rest_field( name="encryptionKey", visibility=["read", "create", "update", "delete", "query"] @@ -5501,6 +5424,7 @@ class KnowledgeBase(_Model): def __init__( self, *, + name: str, knowledge_sources: list["_models.KnowledgeSourceReference"], models: Optional[list["_models.KnowledgeBaseModel"]] = None, retrieval_reasoning_effort: Optional["_knowledgebase_models3.KnowledgeRetrievalReasoningEffort"] = None, @@ -5862,28 +5786,9 @@ class ListSkillsetsResult(_Model): :vartype skillsets: list[~azure.search.documents.indexes.models.SearchIndexerSkillset] """ - skillsets: list["_models.SearchIndexerSkillset"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) + skillsets: list["_models.SearchIndexerSkillset"] = rest_field(name="value", visibility=["read"]) """The skillsets defined in the Search service. Required.""" - @overload - def __init__( - self, - *, - skillsets: list["_models.SearchIndexerSkillset"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class ListSynonymMapsResult(_Model): """Response from a List SynonymMaps request. If successful, it includes the full definitions of @@ -5893,28 +5798,9 @@ class ListSynonymMapsResult(_Model): :vartype synonym_maps: list[~azure.search.documents.indexes.models.SynonymMap] """ - synonym_maps: list["_models.SynonymMap"] = rest_field( - name="value", visibility=["read", "create", "update", "delete", "query"] - ) + synonym_maps: list["_models.SynonymMap"] = rest_field(name="value", visibility=["read"]) """The synonym maps in the Search service. Required.""" - @overload - def __init__( - self, - *, - synonym_maps: list["_models.SynonymMap"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class LuceneStandardAnalyzer(LexicalAnalyzer, discriminator="#Microsoft.Azure.Search.StandardAnalyzer"): """Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop @@ -6410,31 +6296,30 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.odata_type = "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy" # type: ignore -class NGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.NGramTokenFilterV2"): +class NGramTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.NGramTokenFilter"): """Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. Required. :vartype name: str - :ivar min_gram: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the - value of maxGram. + :ivar min_gram: The minimum n-gram length. Default is 1. Must be less than the value of + maxGram. :vartype min_gram: int - :ivar max_gram: The maximum n-gram length. Default is 2. Maximum is 300. + :ivar max_gram: The maximum n-gram length. Default is 2. :vartype max_gram: int :ivar odata_type: A URI fragment specifying the type of token filter. Required. Default value - is "#Microsoft.Azure.Search.NGramTokenFilterV2". + is "#Microsoft.Azure.Search.NGramTokenFilter". :vartype odata_type: str """ min_gram: Optional[int] = rest_field(name="minGram", visibility=["read", "create", "update", "delete", "query"]) - """The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - maxGram.""" + """The minimum n-gram length. Default is 1. Must be less than the value of maxGram.""" max_gram: Optional[int] = rest_field(name="maxGram", visibility=["read", "create", "update", "delete", "query"]) - """The maximum n-gram length. Default is 2. Maximum is 300.""" - odata_type: Literal["#Microsoft.Azure.Search.NGramTokenFilterV2"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The maximum n-gram length. Default is 2.""" + odata_type: Literal["#Microsoft.Azure.Search.NGramTokenFilter"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """A URI fragment specifying the type of token filter. Required. Default value is - \"#Microsoft.Azure.Search.NGramTokenFilterV2\".""" + \"#Microsoft.Azure.Search.NGramTokenFilter\".""" @overload def __init__( @@ -6454,7 +6339,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.odata_type = "#Microsoft.Azure.Search.NGramTokenFilterV2" # type: ignore + self.odata_type = "#Microsoft.Azure.Search.NGramTokenFilter" # type: ignore class NGramTokenizer(LexicalTokenizer, discriminator="#Microsoft.Azure.Search.NGramTokenizer"): @@ -7262,16 +7147,6 @@ class ScalarQuantizationCompression(VectorSearchCompression, discriminator="scal :ivar compression_name: The name to associate with this particular configuration. Required. :vartype compression_name: str - :ivar rerank_with_original_vectors: If set to true, once the ordered set of results calculated - using compressed vectors are obtained, they will be reranked again by recalculating the - full-precision similarity scores. This will improve recall at the expense of latency. - :vartype rerank_with_original_vectors: bool - :ivar default_oversampling: Default oversampling factor. Oversampling will internally request - more documents (specified by this multiplier) in the initial search. This increases the set of - results that will be reranked using recomputed similarity scores from full-precision vectors. - Minimum value is 1, meaning no oversampling (1x). This parameter can only be set when - rerankWithOriginalVectors is true. Higher values improve recall at the expense of latency. - :vartype default_oversampling: float :ivar rescoring_options: Contains the options for rescoring. :vartype rescoring_options: ~azure.search.documents.indexes.models.RescoringOptions :ivar truncation_dimension: The number of dimensions to truncate the vectors to. Truncating the @@ -7307,8 +7182,6 @@ def __init__( self, *, compression_name: str, - rerank_with_original_vectors: Optional[bool] = None, - default_oversampling: Optional[float] = None, rescoring_options: Optional["_models.RescoringOptions"] = None, truncation_dimension: Optional[int] = None, parameters: Optional["_models.ScalarQuantizationParameters"] = None, @@ -7369,7 +7242,7 @@ class ScoringProfile(_Model): :vartype functions: list[~azure.search.documents.indexes.models.ScoringFunction] :ivar function_aggregation: A value indicating how the results of individual scoring functions should be combined. Defaults to "Sum". Ignored if there are no scoring functions. Known values - are: "sum", "average", "minimum", "maximum", and "firstMatching". + are: "sum", "average", "minimum", "maximum", "firstMatching", and "product". :vartype function_aggregation: str or ~azure.search.documents.indexes.models.ScoringFunctionAggregation """ @@ -7389,7 +7262,7 @@ class ScoringProfile(_Model): ) """A value indicating how the results of individual scoring functions should be combined. Defaults to \"Sum\". Ignored if there are no scoring functions. Known values are: \"sum\", \"average\", - \"minimum\", \"maximum\", and \"firstMatching\".""" + \"minimum\", \"maximum\", \"firstMatching\", and \"product\".""" @overload def __init__( @@ -7523,6 +7396,9 @@ class SearchField(_Model): :ivar permission_filter: A value indicating whether the field should be used as a permission filter. Known values are: "userIds", "groupIds", and "rbacScope". :vartype permission_filter: str or ~azure.search.documents.indexes.models.PermissionFilter + :ivar sensitivity_label: A value indicating whether the field contains sensitivity label + information. + :vartype sensitivity_label: bool :ivar analyzer_name: The name of the analyzer to use for the field. This option can be used only with searchable fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed for the field. Must be null @@ -7686,6 +7562,10 @@ class SearchField(_Model): ) """A value indicating whether the field should be used as a permission filter. Known values are: \"userIds\", \"groupIds\", and \"rbacScope\".""" + sensitivity_label: Optional[bool] = rest_field( + name="sensitivityLabel", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether the field contains sensitivity label information.""" analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = rest_field( name="analyzer", visibility=["read", "create", "update", "delete", "query"] ) @@ -7813,6 +7693,7 @@ def __init__( sortable: Optional[bool] = None, facetable: Optional[bool] = None, permission_filter: Optional[Union[str, "_models.PermissionFilter"]] = None, + sensitivity_label: Optional[bool] = None, analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, search_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, index_analyzer_name: Optional[Union[str, "_models.LexicalAnalyzerName"]] = None, @@ -7888,6 +7769,8 @@ class SearchIndex(_Model): the index. Known values are: "enabled" and "disabled". :vartype permission_filter_option: str or ~azure.search.documents.indexes.models.SearchIndexPermissionFilterOption + :ivar purview_enabled: A value indicating whether Purview is enabled for the index. + :vartype purview_enabled: bool :ivar e_tag: The ETag of the index. :vartype e_tag: str """ @@ -7965,6 +7848,10 @@ class SearchIndex(_Model): ) """A value indicating whether permission filtering is enabled for the index. Known values are: \"enabled\" and \"disabled\".""" + purview_enabled: Optional[bool] = rest_field( + name="purviewEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """A value indicating whether Purview is enabled for the index.""" e_tag: Optional[str] = rest_field(name="@odata.etag", visibility=["read", "create", "update", "delete", "query"]) """The ETag of the index.""" @@ -7989,6 +7876,7 @@ def __init__( semantic_search: Optional["_models.SemanticSearch"] = None, vector_search: Optional["_models.VectorSearch"] = None, permission_filter_option: Optional[Union[str, "_models.SearchIndexPermissionFilterOption"]] = None, + purview_enabled: Optional[bool] = None, e_tag: Optional[str] = None, ) -> None: ... @@ -8136,6 +8024,8 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class SearchIndexerCache(_Model): """The type of the cache. + :ivar id: A guid for the SearchIndexerCache. + :vartype id: str :ivar storage_connection_string: The connection string to the storage account where the cache data will be persisted. :vartype storage_connection_string: str @@ -8147,10 +8037,10 @@ class SearchIndexerCache(_Model): unspecified, the value remains unchanged. If set to "none", the value of this property is cleared. :vartype identity: ~azure.search.documents.indexes.models.SearchIndexerDataIdentity - :ivar id: A guid for the SearchIndexerCache. - :vartype id: str """ + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A guid for the SearchIndexerCache.""" storage_connection_string: Optional[str] = rest_field( name="storageConnectionString", visibility=["read", "create", "update", "delete", "query"] ) @@ -8167,17 +8057,15 @@ class SearchIndexerCache(_Model): system-assigned managed identity is used. On updates to the indexer, if the identity is unspecified, the value remains unchanged. If set to \"none\", the value of this property is cleared.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A guid for the SearchIndexerCache.""" @overload def __init__( self, *, + id: Optional[str] = None, # pylint: disable=redefined-builtin storage_connection_string: Optional[str] = None, enable_reprocessing: Optional[bool] = None, identity: Optional["_models.SearchIndexerDataIdentity"] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin ) -> None: ... @overload @@ -8301,7 +8189,7 @@ class SearchIndexerDataSourceConnection(_Model): :ivar description: The description of the datasource. :vartype description: str :ivar type: The type of the datasource. Required. Known values are: "azuresql", "cosmosdb", - "azureblob", "azuretable", "mysql", "adlsgen2", and "onelake". + "azureblob", "azuretable", "mysql", "adlsgen2", "onelake", and "sharepoint". :vartype type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType :ivar sub_type: A specific type of the data source, in case the resource is capable of different modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts. @@ -8345,8 +8233,8 @@ class SearchIndexerDataSourceConnection(_Model): visibility=["read", "create", "update", "delete", "query"] ) """The type of the datasource. Required. Known values are: \"azuresql\", \"cosmosdb\", - \"azureblob\", \"azuretable\", \"mysql\", \"adlsgen2\", and \"onelake\".""" - sub_type: Optional[str] = rest_field(name="subType", visibility=["read", "create", "update", "delete", "query"]) + \"azureblob\", \"azuretable\", \"mysql\", \"adlsgen2\", \"onelake\", and \"sharepoint\".""" + sub_type: Optional[str] = rest_field(name="subType", visibility=["read"]) """A specific type of the data source, in case the resource is capable of different modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts.""" credentials: "_models.DataSourceCredentials" = rest_field( @@ -8400,7 +8288,6 @@ def __init__( credentials: "_models.DataSourceCredentials", container: "_models.SearchIndexerDataContainer", description: Optional[str] = None, - sub_type: Optional[str] = None, identity: Optional["_models.SearchIndexerDataIdentity"] = None, indexer_permission_options: Optional[list[Union[str, "_models.IndexerPermissionOption"]]] = None, data_change_detection_policy: Optional["_models.DataChangeDetectionPolicy"] = None, @@ -9017,18 +8904,22 @@ class SearchIndexerKnowledgeStoreTableProjectionSelector( :ivar reference_key_name: Name of reference key to different projection. :vartype reference_key_name: str - :ivar generated_key_name: Name of generated key to store projection under. - :vartype generated_key_name: str :ivar source: Source data to project. :vartype source: str :ivar source_context: Source context for complex projections. :vartype source_context: str :ivar inputs: Nested inputs for complex projections. :vartype inputs: list[~azure.search.documents.indexes.models.InputFieldMappingEntry] + :ivar generated_key_name: Name of generated key to store projection under. Required. + :vartype generated_key_name: str :ivar table_name: Name of the Azure table to store projected data in. Required. :vartype table_name: str """ + generated_key_name: str = rest_field( + name="generatedKeyName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of generated key to store projection under. Required.""" table_name: str = rest_field(name="tableName", visibility=["read", "create", "update", "delete", "query"]) """Name of the Azure table to store projected data in. Required.""" @@ -9036,9 +8927,9 @@ class SearchIndexerKnowledgeStoreTableProjectionSelector( def __init__( self, *, + generated_key_name: str, table_name: str, reference_key_name: Optional[str] = None, - generated_key_name: Optional[str] = None, source: Optional[str] = None, source_context: Optional[str] = None, inputs: Optional[list["_models.InputFieldMappingEntry"]] = None, @@ -9198,6 +9089,9 @@ class SearchIndexerStatus(_Model): :ivar status: Overall indexer status. Required. Known values are: "unknown", "error", and "running". :vartype status: str or ~azure.search.documents.indexes.models.IndexerStatus + :ivar runtime: Snapshot of the indexer's cumulative runtime consumption for the service over + the current UTC period. Required. + :vartype runtime: ~search.models.IndexerRuntime :ivar last_result: The result of the most recent or an in-progress indexer execution. :vartype last_result: ~azure.search.documents.indexes.models.IndexerExecutionResult :ivar execution_history: History of the recent indexer executions, sorted in reverse @@ -9205,43 +9099,26 @@ class SearchIndexerStatus(_Model): :vartype execution_history: list[~azure.search.documents.indexes.models.IndexerExecutionResult] :ivar limits: The execution limits for the indexer. Required. :vartype limits: ~azure.search.documents.indexes.models.SearchIndexerLimits + :ivar current_state: All of the state that defines and dictates the indexer's current + execution. + :vartype current_state: ~azure.search.documents.indexes.models.IndexerCurrentState """ - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + name: str = rest_field(visibility=["read"]) """The name of the indexer. Required.""" - status: Union[str, "_models.IndexerStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + status: Union[str, "_models.IndexerStatus"] = rest_field(visibility=["read"]) """Overall indexer status. Required. Known values are: \"unknown\", \"error\", and \"running\".""" - last_result: Optional["_models.IndexerExecutionResult"] = rest_field( - name="lastResult", visibility=["read", "create", "update", "delete", "query"] - ) + runtime: "_search_models6.IndexerRuntime" = rest_field(visibility=["read"]) + """Snapshot of the indexer's cumulative runtime consumption for the service over the current UTC + period. Required.""" + last_result: Optional["_models.IndexerExecutionResult"] = rest_field(name="lastResult", visibility=["read"]) """The result of the most recent or an in-progress indexer execution.""" - execution_history: list["_models.IndexerExecutionResult"] = rest_field( - name="executionHistory", visibility=["read", "create", "update", "delete", "query"] - ) + execution_history: list["_models.IndexerExecutionResult"] = rest_field(name="executionHistory", visibility=["read"]) """History of the recent indexer executions, sorted in reverse chronological order. Required.""" - limits: "_models.SearchIndexerLimits" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + limits: "_models.SearchIndexerLimits" = rest_field(visibility=["read"]) """The execution limits for the indexer. Required.""" - - @overload - def __init__( - self, - *, - name: str, - status: Union[str, "_models.IndexerStatus"], - execution_history: list["_models.IndexerExecutionResult"], - limits: "_models.SearchIndexerLimits", - last_result: Optional["_models.IndexerExecutionResult"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + current_state: Optional["_models.IndexerCurrentState"] = rest_field(name="currentState", visibility=["read"]) + """All of the state that defines and dictates the indexer's current execution.""" class SearchIndexerWarning(_Model): @@ -9263,43 +9140,20 @@ class SearchIndexerWarning(_Model): :vartype documentation_link: str """ - key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + key: Optional[str] = rest_field(visibility=["read"]) """The key of the item which generated a warning.""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + message: str = rest_field(visibility=["read"]) """The message describing the warning that occurred while processing the item. Required.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + name: Optional[str] = rest_field(visibility=["read"]) """The name of the source at which the warning originated. For example, this could refer to a particular skill in the attached skillset. This may not be always available.""" - details: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + details: Optional[str] = rest_field(visibility=["read"]) """Additional, verbose details about the warning to assist in debugging the indexer. This may not be always available.""" - documentation_link: Optional[str] = rest_field( - name="documentationLink", visibility=["read", "create", "update", "delete", "query"] - ) + documentation_link: Optional[str] = rest_field(name="documentationLink", visibility=["read"]) """A link to a troubleshooting guide for these classes of warnings. This may not be always available.""" - @overload - def __init__( - self, - *, - message: str, - key: Optional[str] = None, - name: Optional[str] = None, - details: Optional[str] = None, - documentation_link: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class SearchIndexKnowledgeSource(KnowledgeSource, discriminator="searchIndex"): """Knowledge Source targeting a search index. @@ -9308,9 +9162,16 @@ class SearchIndexKnowledgeSource(KnowledgeSource, discriminator="searchIndex"): :vartype name: str :ivar description: Optional user-defined description. :vartype description: str - :ivar e_tag: The ETag of the agent. + :ivar e_tag: The ETag of the knowledge source. :vartype e_tag: str :ivar encryption_key: A description of an encryption key that you create in Azure Key Vault. + This key is used to provide an additional level of encryption-at-rest for your knowledge source + definition when you want full assurance that no one, not even Microsoft, can decrypt them. Once + you have encrypted your knowledge source definition, it will always remain encrypted. The + search service will ignore attempts to set this property to null. You can change this property + as needed if you want to rotate your encryption key; Your knowledge source definition will be + unaffected. Encryption with customer-managed keys is not available for free search services, + and is only available for paid services created on or after January 1, 2019. :vartype encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey :ivar kind: Required. A knowledge source that reads data from a Search Index. :vartype kind: str or ~azure.search.documents.indexes.models.SEARCH_INDEX @@ -9330,6 +9191,7 @@ class SearchIndexKnowledgeSource(KnowledgeSource, discriminator="searchIndex"): def __init__( self, *, + name: str, search_index_parameters: "_models.SearchIndexKnowledgeSourceParameters", description: Optional[str] = None, e_tag: Optional[str] = None, @@ -9353,25 +9215,41 @@ class SearchIndexKnowledgeSourceParameters(_Model): :ivar search_index_name: The name of the Search index. Required. :vartype search_index_name: str - :ivar source_data_select: Used to request additional fields for referenced source data. - :vartype source_data_select: str + :ivar source_data_fields: Used to request additional fields for referenced source data. + :vartype source_data_fields: list[~search.models.SearchIndexFieldReference] + :ivar search_fields: Used to restrict which fields to search on the search index. + :vartype search_fields: list[~search.models.SearchIndexFieldReference] + :ivar semantic_configuration_name: Used to specify a different semantic configuration on the + target search index other than the default one. + :vartype semantic_configuration_name: str """ search_index_name: str = rest_field( name="searchIndexName", visibility=["read", "create", "update", "delete", "query"] ) """The name of the Search index. Required.""" - source_data_select: Optional[str] = rest_field( - name="sourceDataSelect", visibility=["read", "create", "update", "delete", "query"] + source_data_fields: Optional[list["_search_models6.SearchIndexFieldReference"]] = rest_field( + name="sourceDataFields", visibility=["read", "create", "update", "delete", "query"] ) """Used to request additional fields for referenced source data.""" + search_fields: Optional[list["_search_models6.SearchIndexFieldReference"]] = rest_field( + name="searchFields", visibility=["read", "create", "update", "delete", "query"] + ) + """Used to restrict which fields to search on the search index.""" + semantic_configuration_name: Optional[str] = rest_field( + name="semanticConfigurationName", visibility=["read", "create", "update", "delete", "query"] + ) + """Used to specify a different semantic configuration on the target search index other than the + default one.""" @overload def __init__( self, *, search_index_name: str, - source_data_select: Optional[str] = None, + source_data_fields: Optional[list["_search_models6.SearchIndexFieldReference"]] = None, + search_fields: Optional[list["_search_models6.SearchIndexFieldReference"]] = None, + semantic_configuration_name: Optional[str] = None, ) -> None: ... @overload @@ -9393,7 +9271,7 @@ class SearchResourceEncryptionKey(_Model): Required. :vartype key_name: str :ivar key_version: The version of your Azure Key Vault key to be used to encrypt your data at - rest. + rest. Required. :vartype key_version: str :ivar vault_uri: The URI of your Azure Key Vault, also referred to as DNS name, that contains the key to be used to encrypt your data at rest. An example URI might be @@ -9412,10 +9290,8 @@ class SearchResourceEncryptionKey(_Model): key_name: str = rest_field(name="keyVaultKeyName", visibility=["read", "create", "update", "delete", "query"]) """The name of your Azure Key Vault key to be used to encrypt your data at rest. Required.""" - key_version: Optional[str] = rest_field( - name="keyVaultKeyVersion", visibility=["read", "create", "update", "delete", "query"] - ) - """The version of your Azure Key Vault key to be used to encrypt your data at rest.""" + key_version: str = rest_field(name="keyVaultKeyVersion", visibility=["read", "create", "update", "delete", "query"]) + """The version of your Azure Key Vault key to be used to encrypt your data at rest. Required.""" vault_uri: str = rest_field(name="keyVaultUri", visibility=["read", "create", "update", "delete", "query"]) """The URI of your Azure Key Vault, also referred to as DNS name, that contains the key to be used to encrypt your data at rest. An example URI might be @@ -9440,8 +9316,8 @@ def __init__( self, *, key_name: str, + key_version: str, vault_uri: str, - key_version: Optional[str] = None, access_credentials: Optional["_models.AzureActiveDirectoryApplicationCredentials"] = None, identity: Optional["_models.SearchIndexerDataIdentity"] = None, ) -> None: ... @@ -9578,6 +9454,9 @@ class SearchServiceLimits(_Model): :vartype max_complex_objects_in_collections_per_document: int :ivar max_storage_per_index_in_bytes: The maximum amount of storage in bytes allowed per index. :vartype max_storage_per_index_in_bytes: int + :ivar max_cumulative_indexer_runtime_seconds: The maximum cumulative indexer runtime in seconds + allowed for the service. + :vartype max_cumulative_indexer_runtime_seconds: int """ max_fields_per_index: Optional[int] = rest_field( @@ -9601,6 +9480,10 @@ class SearchServiceLimits(_Model): name="maxStoragePerIndex", visibility=["read", "create", "update", "delete", "query"] ) """The maximum amount of storage in bytes allowed per index.""" + max_cumulative_indexer_runtime_seconds: Optional[int] = rest_field( + name="maxCumulativeIndexerRuntimeSeconds", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum cumulative indexer runtime in seconds allowed for the service.""" @overload def __init__( @@ -9611,6 +9494,7 @@ def __init__( max_complex_collection_fields_per_index: Optional[int] = None, max_complex_objects_in_collections_per_document: Optional[int] = None, max_storage_per_index_in_bytes: Optional[int] = None, + max_cumulative_indexer_runtime_seconds: Optional[int] = None, ) -> None: ... @overload @@ -9632,12 +9516,18 @@ class SearchServiceStatistics(_Model): :vartype counters: ~azure.search.documents.indexes.models.SearchServiceCounters :ivar limits: Service level general limits. Required. :vartype limits: ~azure.search.documents.indexes.models.SearchServiceLimits + :ivar indexers_runtime: Service level indexer runtime consumption. Required. + :vartype indexers_runtime: ~search.models.ServiceIndexersRuntime """ counters: "_models.SearchServiceCounters" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Service level resource counters. Required.""" limits: "_models.SearchServiceLimits" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Service level general limits. Required.""" + indexers_runtime: "_search_models6.ServiceIndexersRuntime" = rest_field( + name="indexersRuntime", visibility=["read", "create", "update", "delete", "query"] + ) + """Service level indexer runtime consumption. Required.""" @overload def __init__( @@ -9645,6 +9535,7 @@ def __init__( *, counters: "_models.SearchServiceCounters", limits: "_models.SearchServiceLimits", + indexers_runtime: "_search_models6.ServiceIndexersRuntime", ) -> None: ... @overload @@ -10461,7 +10352,9 @@ class StemmerOverrideTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Se """Provides the ability to override other stemming filters with custom dictionary-based stemming. Any dictionary-stemmed terms will be marked as keywords so that they will not be stemmed with stemmers down the chain. Must be placed before any stemming filters. This token filter is - implemented using Apache Lucene. + implemented using Apache Lucene. See + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.html + `_. :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 @@ -10503,7 +10396,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class StemmerTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StemmerTokenFilter"): - """Language specific stemming filter. This token filter is implemented using Apache Lucene. + """Language specific stemming filter. This token filter is implemented using Apache Lucene. See + `https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters + `_. :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 @@ -10605,6 +10500,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class StopwordsTokenFilter(TokenFilter, discriminator="#Microsoft.Azure.Search.StopwordsTokenFilter"): """Removes stop words from a token stream. This token filter is implemented using Apache Lucene. + See + `http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html + `_. :ivar name: The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 @@ -11306,16 +11204,18 @@ class VisionVectorizeSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills. be consumed as an input by another skill. Required. :vartype outputs: list[~azure.search.documents.indexes.models.OutputFieldMappingEntry] :ivar model_version: The version of the model to use when calling the AI Services Vision - service. It will default to the latest available when not specified. Required. + service. It will default to the latest available when not specified. :vartype model_version: str :ivar odata_type: A URI fragment specifying the type of skill. Required. Default value is "#Microsoft.Skills.Vision.VectorizeSkill". :vartype odata_type: str """ - model_version: str = rest_field(name="modelVersion", visibility=["read", "create", "update", "delete", "query"]) + model_version: Optional[str] = rest_field( + name="modelVersion", visibility=["read", "create", "update", "delete", "query"] + ) """The version of the model to use when calling the AI Services Vision service. It will default to - the latest available when not specified. Required.""" + the latest available when not specified.""" odata_type: Literal["#Microsoft.Skills.Vision.VectorizeSkill"] = rest_discriminator(name="@odata.type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """A URI fragment specifying the type of skill. Required. Default value is \"#Microsoft.Skills.Vision.VectorizeSkill\".""" @@ -11326,10 +11226,10 @@ def __init__( *, inputs: list["_models.InputFieldMappingEntry"], outputs: list["_models.OutputFieldMappingEntry"], - model_version: str, name: Optional[str] = None, description: Optional[str] = None, context: Optional[str] = None, + model_version: Optional[str] = None, ) -> None: ... @overload @@ -11371,7 +11271,7 @@ class WebApiSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.We :ivar uri: The url for the Web API. Required. :vartype uri: str :ivar http_headers: The headers required to make the http request. - :vartype http_headers: dict[str, str] + :vartype http_headers: ~azure.search.documents.indexes.models.WebApiHttpHeaders :ivar http_method: The method for the http request. :vartype http_method: str :ivar timeout: The desired timeout for the request. Default is 30 seconds. @@ -11400,7 +11300,7 @@ class WebApiSkill(SearchIndexerSkill, discriminator="#Microsoft.Skills.Custom.We uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The url for the Web API. Required.""" - http_headers: Optional[dict[str, str]] = rest_field( + http_headers: Optional["_models.WebApiHttpHeaders"] = rest_field( name="httpHeaders", visibility=["read", "create", "update", "delete", "query"] ) """The headers required to make the http request.""" @@ -11446,7 +11346,7 @@ def __init__( name: Optional[str] = None, description: Optional[str] = None, context: Optional[str] = None, - http_headers: Optional[dict[str, str]] = None, + http_headers: Optional["_models.WebApiHttpHeaders"] = None, http_method: Optional[str] = None, timeout: Optional[datetime.timedelta] = None, batch_size: Optional[int] = None, diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py index f800324958aa..cc96c5529b72 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py @@ -37,7 +37,6 @@ KnowledgeBaseRetrievalResponse, KnowledgeBaseSearchIndexReference, KnowledgeBaseWebReference, - KnowledgeRetrievalHighReasoningEffort, KnowledgeRetrievalIntent, KnowledgeRetrievalLowReasoningEffort, KnowledgeRetrievalMediumReasoningEffort, @@ -85,7 +84,6 @@ "KnowledgeBaseRetrievalResponse", "KnowledgeBaseSearchIndexReference", "KnowledgeBaseWebReference", - "KnowledgeRetrievalHighReasoningEffort", "KnowledgeRetrievalIntent", "KnowledgeRetrievalLowReasoningEffort", "KnowledgeRetrievalMediumReasoningEffort", diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py index 31ccafa2e2fb..c9d1cd20f6b3 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_enums.py @@ -39,10 +39,8 @@ class KnowledgeRetrievalReasoningEffortKind(str, Enum, metaclass=CaseInsensitive """The amount of effort to use during retrieval.""" MINIMAL = "minimal" - """Does not perform any source selections, any query planning, or any iterative search.""" + """Does not perform any source selections, query planning, or iterative search.""" LOW = "low" """Use low reasoning during retrieval.""" MEDIUM = "medium" """Use a moderate amount of reasoning during retrieval.""" - HIGH = "high" - """Use a high amount of reasoning during retrieval.""" diff --git a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py index 34f74d089118..6724a4f3f157 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/_models.py @@ -10,6 +10,7 @@ from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload +from ......search.models._enums import KnowledgeBaseActivityRecordType, KnowledgeBaseReferenceType from ..._utils.model_base import Model as _Model, rest_discriminator, rest_field from ...indexes.models._enums import KnowledgeSourceKind from ._enums import KnowledgeBaseMessageContentType, KnowledgeRetrievalIntentType, KnowledgeRetrievalReasoningEffortKind @@ -241,7 +242,8 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class KnowledgeBaseActivityRecord(_Model): - """Base type for activity records. + """Base type for activity records. Tracks execution details, timing, and errors for knowledge base + operations. You probably want to use the sub-classes and not this class directly. Known sub-classes are: KnowledgeBaseAgenticReasoningActivityRecord, KnowledgeBaseModelAnswerSynthesisActivityRecord, @@ -249,8 +251,10 @@ class KnowledgeBaseActivityRecord(_Model): :ivar id: The ID of the activity record. Required. :vartype id: int - :ivar type: The type of the activity record. Required. Default value is None. - :vartype type: str + :ivar type: The type of the activity record. Required. Known values are: "searchIndex", + "azureBlob", "indexedSharePoint", "indexedOneLake", "web", "remoteSharePoint", + "modelQueryPlanning", "modelAnswerSynthesis", and "agenticReasoning". + :vartype type: str or ~search.models.KnowledgeBaseActivityRecordType :ivar elapsed_ms: The elapsed time in milliseconds for the retrieval activity. :vartype elapsed_ms: int :ivar error: The error detail explaining why the operation failed. This property is only @@ -262,7 +266,9 @@ class KnowledgeBaseActivityRecord(_Model): id: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The ID of the activity record. Required.""" type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of the activity record. Required. Default value is None.""" + """The type of the activity record. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", \"remoteSharePoint\", + \"modelQueryPlanning\", \"modelAnswerSynthesis\", and \"agenticReasoning\".""" elapsed_ms: Optional[int] = rest_field(name="elapsedMs", visibility=["read", "create", "update", "delete", "query"]) """The elapsed time in milliseconds for the retrieval activity.""" error: Optional["_models.KnowledgeBaseErrorDetail"] = rest_field( @@ -304,8 +310,8 @@ class KnowledgeBaseAgenticReasoningActivityRecord( :ivar error: The error detail explaining why the operation failed. This property is only included when the activity does not succeed. :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail - :ivar type: The discriminator value. Required. Default value is "agenticReasoning". - :vartype type: str + :ivar type: The discriminator value. Required. Agentic reasoning activity. + :vartype type: str or ~search.models.AGENTIC_REASONING :ivar reasoning_tokens: The number of input tokens for agentic reasoning. :vartype reasoning_tokens: int :ivar retrieval_reasoning_effort: The retrieval reasoning effort configuration. @@ -313,8 +319,8 @@ class KnowledgeBaseAgenticReasoningActivityRecord( ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffort """ - type: Literal["agenticReasoning"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"agenticReasoning\".""" + type: Literal[KnowledgeBaseActivityRecordType.AGENTIC_REASONING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Agentic reasoning activity.""" reasoning_tokens: Optional[int] = rest_field( name="reasoningTokens", visibility=["read", "create", "update", "delete", "query"] ) @@ -344,7 +350,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "agenticReasoning" # type: ignore + self.type = KnowledgeBaseActivityRecordType.AGENTIC_REASONING # type: ignore class KnowledgeBaseReference(_Model): @@ -355,26 +361,28 @@ class KnowledgeBaseReference(_Model): KnowledgeBaseIndexedSharePointReference, KnowledgeBaseRemoteSharePointReference, KnowledgeBaseSearchIndexReference, KnowledgeBaseWebReference - :ivar type: The type of the reference. Required. Default value is None. - :vartype type: str + :ivar type: The type of the reference. Required. Known values are: "searchIndex", "azureBlob", + "indexedSharePoint", "indexedOneLake", "web", and "remoteSharePoint". + :vartype type: str or ~search.models.KnowledgeBaseReferenceType :ivar id: The ID of the reference. Required. :vartype id: str :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float """ __mapping__: dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of the reference. Required. Default value is None.""" + """The type of the reference. Required. Known values are: \"searchIndex\", \"azureBlob\", + \"indexedSharePoint\", \"indexedOneLake\", \"web\", and \"remoteSharePoint\".""" id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The ID of the reference. Required.""" activity_source: int = rest_field(name="activitySource", visibility=["read", "create", "update", "delete", "query"]) """The source activity ID for the reference. Required.""" - source_data: Optional[dict[str, str]] = rest_field( + source_data: Optional[dict[str, Any]] = rest_field( name="sourceData", visibility=["read", "create", "update", "delete", "query"] ) """The source data for the reference.""" @@ -390,7 +398,7 @@ def __init__( type: str, id: str, # pylint: disable=redefined-builtin activity_source: int, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, ) -> None: ... @@ -413,17 +421,17 @@ class KnowledgeBaseAzureBlobReference(KnowledgeBaseReference, discriminator="azu :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float - :ivar type: The discriminator value. Required. Default value is "azureBlob". - :vartype type: str + :ivar type: The discriminator value. Required. Azure Blob document reference. + :vartype type: str or ~search.models.AZURE_BLOB :ivar blob_url: The blob URL for the reference. :vartype blob_url: str """ - type: Literal["azureBlob"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"azureBlob\".""" + type: Literal[KnowledgeBaseReferenceType.AZURE_BLOB] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Azure Blob document reference.""" blob_url: Optional[str] = rest_field(name="blobUrl", visibility=["read", "create", "update", "delete", "query"]) """The blob URL for the reference.""" @@ -433,7 +441,7 @@ def __init__( *, id: str, # pylint: disable=redefined-builtin activity_source: int, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, blob_url: Optional[str] = None, ) -> None: ... @@ -447,7 +455,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "azureBlob" # type: ignore + self.type = KnowledgeBaseReferenceType.AZURE_BLOB # type: ignore class KnowledgeBaseErrorAdditionalInfo(_Model): @@ -456,32 +464,14 @@ class KnowledgeBaseErrorAdditionalInfo(_Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: dict[str, str] + :vartype info: dict[str, any] """ - type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + type: Optional[str] = rest_field(visibility=["read"]) """The additional info type.""" - info: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + info: Optional[dict[str, Any]] = rest_field(visibility=["read"]) """The additional info.""" - @overload - def __init__( - self, - *, - type: Optional[str] = None, - info: Optional[dict[str, str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class KnowledgeBaseErrorDetail(_Model): """The error details. @@ -499,42 +489,19 @@ class KnowledgeBaseErrorDetail(_Model): list[~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorAdditionalInfo] """ - code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + code: Optional[str] = rest_field(visibility=["read"]) """The error code.""" - message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + message: Optional[str] = rest_field(visibility=["read"]) """The error message.""" - target: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + target: Optional[str] = rest_field(visibility=["read"]) """The error target.""" - details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) + details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = rest_field(visibility=["read"]) """The error details.""" additional_info: Optional[list["_models.KnowledgeBaseErrorAdditionalInfo"]] = rest_field( - name="additionalInfo", visibility=["read", "create", "update", "delete", "query"] + name="additionalInfo", visibility=["read"] ) """The error additional info.""" - @overload - def __init__( - self, - *, - code: Optional[str] = None, - message: Optional[str] = None, - target: Optional[str] = None, - details: Optional[list["_models.KnowledgeBaseErrorDetail"]] = None, - additional_info: Optional[list["_models.KnowledgeBaseErrorAdditionalInfo"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class KnowledgeBaseImageContent(_Model): """Image content. @@ -572,17 +539,17 @@ class KnowledgeBaseIndexedOneLakeReference(KnowledgeBaseReference, discriminator :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float - :ivar type: The discriminator value. Required. Default value is "indexedOneLake". - :vartype type: str + :ivar type: The discriminator value. Required. Indexed OneLake document reference. + :vartype type: str or ~search.models.INDEXED_ONE_LAKE :ivar doc_url: The document URL for the reference. :vartype doc_url: str """ - type: Literal["indexedOneLake"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"indexedOneLake\".""" + type: Literal[KnowledgeBaseReferenceType.INDEXED_ONE_LAKE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Indexed OneLake document reference.""" doc_url: Optional[str] = rest_field(name="docUrl", visibility=["read", "create", "update", "delete", "query"]) """The document URL for the reference.""" @@ -592,7 +559,7 @@ def __init__( *, id: str, # pylint: disable=redefined-builtin activity_source: int, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, doc_url: Optional[str] = None, ) -> None: ... @@ -606,7 +573,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "indexedOneLake" # type: ignore + self.type = KnowledgeBaseReferenceType.INDEXED_ONE_LAKE # type: ignore class KnowledgeBaseIndexedSharePointReference(KnowledgeBaseReference, discriminator="indexedSharePoint"): @@ -617,17 +584,17 @@ class KnowledgeBaseIndexedSharePointReference(KnowledgeBaseReference, discrimina :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float - :ivar type: The discriminator value. Required. Default value is "indexedSharePoint". - :vartype type: str + :ivar type: The discriminator value. Required. Indexed SharePoint document reference. + :vartype type: str or ~search.models.INDEXED_SHARE_POINT :ivar doc_url: The document URL for the reference. :vartype doc_url: str """ - type: Literal["indexedSharePoint"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"indexedSharePoint\".""" + type: Literal[KnowledgeBaseReferenceType.INDEXED_SHARE_POINT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Indexed SharePoint document reference.""" doc_url: Optional[str] = rest_field(name="docUrl", visibility=["read", "create", "update", "delete", "query"]) """The document URL for the reference.""" @@ -637,7 +604,7 @@ def __init__( *, id: str, # pylint: disable=redefined-builtin activity_source: int, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, doc_url: Optional[str] = None, ) -> None: ... @@ -651,7 +618,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "indexedSharePoint" # type: ignore + self.type = KnowledgeBaseReferenceType.INDEXED_SHARE_POINT # type: ignore class KnowledgeBaseMessage(_Model): @@ -801,16 +768,16 @@ class KnowledgeBaseModelAnswerSynthesisActivityRecord( :ivar error: The error detail explaining why the operation failed. This property is only included when the activity does not succeed. :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail - :ivar type: The discriminator value. Required. Default value is "modelAnswerSynthesis". - :vartype type: str + :ivar type: The discriminator value. Required. LLM answer synthesis activity. + :vartype type: str or ~search.models.MODEL_ANSWER_SYNTHESIS :ivar input_tokens: The number of input tokens for the LLM answer synthesis activity. :vartype input_tokens: int :ivar output_tokens: The number of output tokens for the LLM answer synthesis activity. :vartype output_tokens: int """ - type: Literal["modelAnswerSynthesis"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"modelAnswerSynthesis\".""" + type: Literal[KnowledgeBaseActivityRecordType.MODEL_ANSWER_SYNTHESIS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. LLM answer synthesis activity.""" input_tokens: Optional[int] = rest_field( name="inputTokens", visibility=["read", "create", "update", "delete", "query"] ) @@ -840,7 +807,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "modelAnswerSynthesis" # type: ignore + self.type = KnowledgeBaseActivityRecordType.MODEL_ANSWER_SYNTHESIS # type: ignore class KnowledgeBaseModelQueryPlanningActivityRecord( @@ -855,16 +822,16 @@ class KnowledgeBaseModelQueryPlanningActivityRecord( :ivar error: The error detail explaining why the operation failed. This property is only included when the activity does not succeed. :vartype error: ~azure.search.documents.knowledgebase.models.KnowledgeBaseErrorDetail - :ivar type: The discriminator value. Required. Default value is "modelQueryPlanning". - :vartype type: str + :ivar type: The discriminator value. Required. LLM query planning activity. + :vartype type: str or ~search.models.MODEL_QUERY_PLANNING :ivar input_tokens: The number of input tokens for the LLM query planning activity. :vartype input_tokens: int :ivar output_tokens: The number of output tokens for the LLM query planning activity. :vartype output_tokens: int """ - type: Literal["modelQueryPlanning"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"modelQueryPlanning\".""" + type: Literal[KnowledgeBaseActivityRecordType.MODEL_QUERY_PLANNING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. LLM query planning activity.""" input_tokens: Optional[int] = rest_field( name="inputTokens", visibility=["read", "create", "update", "delete", "query"] ) @@ -894,7 +861,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "modelQueryPlanning" # type: ignore + self.type = KnowledgeBaseActivityRecordType.MODEL_QUERY_PLANNING # type: ignore class KnowledgeBaseRemoteSharePointReference(KnowledgeBaseReference, discriminator="remoteSharePoint"): @@ -905,11 +872,11 @@ class KnowledgeBaseRemoteSharePointReference(KnowledgeBaseReference, discriminat :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float - :ivar type: The discriminator value. Required. Default value is "remoteSharePoint". - :vartype type: str + :ivar type: The discriminator value. Required. Remote SharePoint document reference. + :vartype type: str or ~search.models.REMOTE_SHARE_POINT :ivar web_url: The url the reference data originated from. Required. :vartype web_url: str :ivar search_sensitivity_label_info: Information about the sensitivity label applied to the @@ -918,8 +885,8 @@ class KnowledgeBaseRemoteSharePointReference(KnowledgeBaseReference, discriminat ~azure.search.documents.knowledgebase.models.SharePointSensitivityLabelInfo """ - type: Literal["remoteSharePoint"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"remoteSharePoint\".""" + type: Literal[KnowledgeBaseReferenceType.REMOTE_SHARE_POINT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Remote SharePoint document reference.""" web_url: str = rest_field(name="webUrl", visibility=["read", "create", "update", "delete", "query"]) """The url the reference data originated from. Required.""" search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = rest_field( @@ -934,7 +901,7 @@ def __init__( id: str, # pylint: disable=redefined-builtin activity_source: int, web_url: str, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, search_sensitivity_label_info: Optional["_models.SharePointSensitivityLabelInfo"] = None, ) -> None: ... @@ -948,7 +915,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "remoteSharePoint" # type: ignore + self.type = KnowledgeBaseReferenceType.REMOTE_SHARE_POINT # type: ignore class KnowledgeBaseRetrievalRequest(_Model): @@ -1088,17 +1055,17 @@ class KnowledgeBaseSearchIndexReference(KnowledgeBaseReference, discriminator="s :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float - :ivar type: The discriminator value. Required. Default value is "searchIndex". - :vartype type: str + :ivar type: The discriminator value. Required. Search index document reference. + :vartype type: str or ~search.models.SEARCH_INDEX :ivar doc_key: The document key for the reference. :vartype doc_key: str """ - type: Literal["searchIndex"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"searchIndex\".""" + type: Literal[KnowledgeBaseReferenceType.SEARCH_INDEX] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Search index document reference.""" doc_key: Optional[str] = rest_field(name="docKey", visibility=["read", "create", "update", "delete", "query"]) """The document key for the reference.""" @@ -1108,7 +1075,7 @@ def __init__( *, id: str, # pylint: disable=redefined-builtin activity_source: int, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, doc_key: Optional[str] = None, ) -> None: ... @@ -1122,7 +1089,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "searchIndex" # type: ignore + self.type = KnowledgeBaseReferenceType.SEARCH_INDEX # type: ignore class KnowledgeBaseWebReference(KnowledgeBaseReference, discriminator="web"): @@ -1133,19 +1100,19 @@ class KnowledgeBaseWebReference(KnowledgeBaseReference, discriminator="web"): :ivar activity_source: The source activity ID for the reference. Required. :vartype activity_source: int :ivar source_data: The source data for the reference. - :vartype source_data: dict[str, str] + :vartype source_data: dict[str, any] :ivar reranker_score: The reranker score for the document reference. :vartype reranker_score: float - :ivar type: The discriminator value. Required. Default value is "web". - :vartype type: str + :ivar type: The discriminator value. Required. Web document reference. + :vartype type: str or ~search.models.WEB :ivar url: The url the reference data originated from. Required. :vartype url: str :ivar title: The title of the web document. :vartype title: str """ - type: Literal["web"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Default value is \"web\".""" + type: Literal[KnowledgeBaseReferenceType.WEB] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The discriminator value. Required. Web document reference.""" url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The url the reference data originated from. Required.""" title: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -1158,7 +1125,7 @@ def __init__( id: str, # pylint: disable=redefined-builtin activity_source: int, url: str, - source_data: Optional[dict[str, str]] = None, + source_data: Optional[dict[str, Any]] = None, reranker_score: Optional[float] = None, title: Optional[str] = None, ) -> None: ... @@ -1172,58 +1139,28 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = "web" # type: ignore + self.type = KnowledgeBaseReferenceType.WEB # type: ignore -class KnowledgeRetrievalReasoningEffort(_Model): - """Base type for reasoning effort. +class KnowledgeRetrievalIntent(_Model): + """An intended query to execute without model query planning. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeRetrievalHighReasoningEffort, KnowledgeRetrievalLowReasoningEffort, - KnowledgeRetrievalMediumReasoningEffort, KnowledgeRetrievalMinimalReasoningEffort + KnowledgeRetrievalSemanticIntent - :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", - "medium", and "high". - :vartype kind: str or - ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffortKind + :ivar type: The type of the intent. Required. "semantic" + :vartype type: str or ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalIntentType """ __mapping__: dict[str, _Model] = {} - kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) - """The kind of reasoning effort. Required. Known values are: \"minimal\", \"low\", \"medium\", and - \"high\".""" + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the intent. Required. \"semantic\"""" @overload def __init__( self, *, - kind: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class KnowledgeRetrievalHighReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="high"): - """Run knowledge retrieval with high reasoning effort. - - :ivar kind: The discriminator value. Required. Use a high amount of reasoning during retrieval. - :vartype kind: str or ~azure.search.documents.knowledgebase.models.HIGH - """ - - kind: Literal[KnowledgeRetrievalReasoningEffortKind.HIGH] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Use a high amount of reasoning during retrieval.""" - - @overload - def __init__( - self, + type: str, ) -> None: ... @overload @@ -1235,28 +1172,30 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.kind = KnowledgeRetrievalReasoningEffortKind.HIGH # type: ignore -class KnowledgeRetrievalIntent(_Model): - """An intended query to execute without model query planning. +class KnowledgeRetrievalReasoningEffort(_Model): + """Base type for reasoning effort. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - KnowledgeRetrievalSemanticIntent + KnowledgeRetrievalLowReasoningEffort, KnowledgeRetrievalMediumReasoningEffort, + KnowledgeRetrievalMinimalReasoningEffort - :ivar type: The type of the intent. Required. "semantic" - :vartype type: str or ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalIntentType + :ivar kind: The kind of reasoning effort. Required. Known values are: "minimal", "low", and + "medium". + :vartype kind: str or + ~azure.search.documents.knowledgebase.models.KnowledgeRetrievalReasoningEffortKind """ __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of the intent. Required. \"semantic\"""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The kind of reasoning effort. Required. Known values are: \"minimal\", \"low\", and \"medium\".""" @overload def __init__( self, *, - type: str, + kind: str, ) -> None: ... @overload @@ -1328,14 +1267,14 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class KnowledgeRetrievalMinimalReasoningEffort(KnowledgeRetrievalReasoningEffort, discriminator="minimal"): """Run knowledge retrieval with minimal reasoning effort. - :ivar kind: The discriminator value. Required. Does not perform any source selections, any - query planning, or any iterative search. + :ivar kind: The discriminator value. Required. Does not perform any source selections, query + planning, or iterative search. :vartype kind: str or ~azure.search.documents.knowledgebase.models.MINIMAL """ kind: Literal[KnowledgeRetrievalReasoningEffortKind.MINIMAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The discriminator value. Required. Does not perform any source selections, any query planning, - or any iterative search.""" + """The discriminator value. Required. Does not perform any source selections, query planning, or + iterative search.""" @overload def __init__( @@ -1407,40 +1346,20 @@ class RemoteSharePointKnowledgeSourceParams(KnowledgeSourceParams, discriminator :ivar kind: The discriminator value. Required. A knowledge source that reads data from remote SharePoint. :vartype kind: str or ~azure.search.documents.indexes.models.REMOTE_SHARE_POINT - :ivar filter_expression: Keyword Query Language (KQL) expression with queryable SharePoint - properties and attributes to scope the retrieval before the query runs. See documentation: - `https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference - `_. - :vartype filter_expression: str - :ivar resource_metadata: A list of metadata fields to be returned for each item in the - response. Only retrievable metadata properties can be included in this list. By default, no - metadata is returned. Optional. - :vartype resource_metadata: list[str] - :ivar container_type_id: Container ID for SharePoint Embedded connection. When this is null, it - will use SharePoint Online. - :vartype container_type_id: str + :ivar filter_expression_add_on: A filter condition applied to the SharePoint data source. It + must be specified in the Keyword Query Language syntax. It will be combined as a conjunction + with the filter expression specified in the knowledge source definition. + :vartype filter_expression_add_on: str """ kind: Literal[KnowledgeSourceKind.REMOTE_SHARE_POINT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The discriminator value. Required. A knowledge source that reads data from remote SharePoint.""" - filter_expression: Optional[str] = rest_field( - name="filterExpression", visibility=["read", "create", "update", "delete", "query"] - ) - """Keyword Query Language (KQL) expression with queryable SharePoint properties and attributes to - scope the retrieval before the query runs. See documentation: - `https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference - `_.""" - resource_metadata: Optional[list[str]] = rest_field( - name="resourceMetadata", visibility=["read", "create", "update", "delete", "query"] - ) - """A list of metadata fields to be returned for each item in the response. Only retrievable - metadata properties can be included in this list. By default, no metadata is returned. - Optional.""" - container_type_id: Optional[str] = rest_field( - name="containerTypeId", visibility=["read", "create", "update", "delete", "query"] + filter_expression_add_on: Optional[str] = rest_field( + name="filterExpressionAddOn", visibility=["read", "create", "update", "delete", "query"] ) - """Container ID for SharePoint Embedded connection. When this is null, it will use SharePoint - Online.""" + """A filter condition applied to the SharePoint data source. It must be specified in the Keyword + Query Language syntax. It will be combined as a conjunction with the filter expression + specified in the knowledge source definition.""" @overload def __init__( @@ -1451,9 +1370,7 @@ def __init__( include_reference_source_data: Optional[bool] = None, always_query_source: Optional[bool] = None, reranker_threshold: Optional[float] = None, - filter_expression: Optional[str] = None, - resource_metadata: Optional[list[str]] = None, - container_type_id: Optional[str] = None, + filter_expression_add_on: Optional[str] = None, ) -> None: ... @overload diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py index 0d5ed03370b5..6aa2bc79fcae 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_enums.py @@ -399,7 +399,8 @@ class VectorFilterMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): PRE_FILTER = "preFilter" """The filter will be applied before the search query.""" STRICT_POST_FILTER = "strictPostFilter" - """The filter will be applied after the global top-k candidate set of vector results is returned.""" + """The filter will be applied after the global top-k candidate set of vector results is returned. + This will result in fewer results than requested by the parameter 'k'.""" class VectorQueryKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -418,7 +419,7 @@ class VectorQueryKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): class VectorThresholdKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The kind of vector query being performed.""" + """The kind of threshold used to filter vector queries.""" VECTOR_SIMILARITY = "vectorSimilarity" """The results of the vector query will be filtered based on the vector similarity metric. Note diff --git a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py index d76287449034..1954980b603c 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/models/_models.py +++ b/sdk/search/azure-search-documents/azure/search/documents/models/_models.py @@ -245,38 +245,38 @@ class FacetResult(_Model): :ivar count: The approximate count of documents falling within the bucket described by this facet. :vartype count: int + :ivar avg: The resulting total avg for the facet when a avg metric is requested. + :vartype avg: float + :ivar min: The resulting total min for the facet when a min metric is requested. + :vartype min: float + :ivar max: The resulting total max for the facet when a max metric is requested. + :vartype max: float + :ivar sum: The resulting total sum for the facet when a sum metric is requested. + :vartype sum: float + :ivar cardinality: The resulting total cardinality for the facet when a cardinality metric is + requested. + :vartype cardinality: int :ivar facets: The nested facet query results for the search operation, organized as a collection of buckets for each faceted field; null if the query did not contain any nested facets. :vartype facets: dict[str, list[~azure.search.documents.models.FacetResult]] - :ivar sum: The resulting total sum for the facet when a sum metric is requested. - :vartype sum: int """ - count: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + count: Optional[int] = rest_field(visibility=["read"]) """The approximate count of documents falling within the bucket described by this facet.""" + avg: Optional[float] = rest_field(visibility=["read"]) + """The resulting total avg for the facet when a avg metric is requested.""" + min: Optional[float] = rest_field(visibility=["read"]) + """The resulting total min for the facet when a min metric is requested.""" + max: Optional[float] = rest_field(visibility=["read"]) + """The resulting total max for the facet when a max metric is requested.""" + sum: Optional[float] = rest_field(visibility=["read"]) + """The resulting total sum for the facet when a sum metric is requested.""" + cardinality: Optional[int] = rest_field(visibility=["read"]) + """The resulting total cardinality for the facet when a cardinality metric is requested.""" facets: Optional[dict[str, list["_models.FacetResult"]]] = rest_field(name="@search.facets", visibility=["read"]) """The nested facet query results for the search operation, organized as a collection of buckets for each faceted field; null if the query did not contain any nested facets.""" - sum: Optional[int] = rest_field(visibility=["read"]) - """The resulting total sum for the facet when a sum metric is requested.""" - - @overload - def __init__( - self, - *, - count: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) class HybridSearch(_Model): @@ -441,42 +441,20 @@ class IndexingResult(_Model): :vartype status_code: int """ - key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + key: str = rest_field(visibility=["read"]) """The key of a document that was in the indexing request. Required.""" - error_message: Optional[str] = rest_field( - name="errorMessage", visibility=["read", "create", "update", "delete", "query"] - ) + error_message: Optional[str] = rest_field(name="errorMessage", visibility=["read"]) """The error message explaining why the indexing operation failed for the document identified by the key; null if indexing succeeded.""" - succeeded: bool = rest_field(name="status", visibility=["read", "create", "update", "delete", "query"]) + succeeded: bool = rest_field(name="status", visibility=["read"]) """A value indicating whether the indexing operation succeeded for the document identified by the key. Required.""" - status_code: int = rest_field(name="statusCode", visibility=["read", "create", "update", "delete", "query"]) + status_code: int = rest_field(name="statusCode", visibility=["read"]) """The status code of the indexing operation. Possible values include: 200 for a successful update or delete, 201 for successful document creation, 400 for a malformed input document, 404 for document not found, 409 for a version conflict, 422 when the index is temporarily unavailable, or 503 for when the service is too busy. Required.""" - @overload - def __init__( - self, - *, - key: str, - succeeded: bool, - status_code: int, - error_message: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - class LookupDocument(_Model): """A document retrieved via a document lookup operation.""" @@ -852,7 +830,7 @@ class SearchRequest(_Model): "eu-es", "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", and "ur-pk". :vartype query_language: str or ~azure.search.documents.models.QueryLanguage - :ivar query_speller: A value that specified the type of the speller to use to spell-correct + :ivar query_speller: A value that specifies the type of the speller to use to spell-correct individual search query terms. Known values are: "none" and "lexicon". :vartype query_speller: str or ~azure.search.documents.models.QuerySpellerType :ivar select: The comma-separated list of fields to retrieve. If unspecified, all fields marked @@ -1009,7 +987,7 @@ class SearchRequest(_Model): query_speller: Optional[Union[str, "_models.QuerySpellerType"]] = rest_field( name="speller", visibility=["read", "create", "update", "delete", "query"] ) - """A value that specified the type of the speller to use to spell-correct individual search query + """A value that specifies the type of the speller to use to spell-correct individual search query terms. Known values are: \"none\" and \"lexicon\".""" select: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The comma-separated list of fields to retrieve. If unspecified, all fields marked as @@ -1152,7 +1130,7 @@ class SearchResult(_Model): :vartype captions: list[~azure.search.documents.models.QueryCaptionResult] :ivar document_debug_info: Contains debugging information that can be used to further explore your search results. - :vartype document_debug_info: list[~azure.search.documents.models.DocumentDebugInfo] + :vartype document_debug_info: ~azure.search.documents.models.DocumentDebugInfo """ score: float = rest_field(name="@search.score", visibility=["read", "create", "update", "delete", "query"]) @@ -1181,7 +1159,7 @@ class SearchResult(_Model): """Captions are the most representative passages from the document relatively to the search query. They are often used as document summary. Captions are only returned for queries of type 'semantic'.""" - document_debug_info: Optional[list["_models.DocumentDebugInfo"]] = rest_field( + document_debug_info: Optional["_models.DocumentDebugInfo"] = rest_field( name="@search.documentDebugInfo", visibility=["read"] ) """Contains debugging information that can be used to further explore your search results.""" @@ -1456,9 +1434,10 @@ class VectorQuery(_Model): no filter expression is defined at the vector level, the expression defined in the top level filter parameter is used instead. :vartype filter_override: str - :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector - query. If no filter expression is defined at the vector level, the expression defined in the - top level filter parameter is used instead. + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. :vartype per_document_vector_limit: int :ivar kind: Type of query. Required. Known values are: "vector", "text", "imageUrl", and "imageBinary". @@ -1501,9 +1480,10 @@ class VectorQuery(_Model): per_document_vector_limit: Optional[int] = rest_field( name="perDocumentVectorLimit", visibility=["read", "create", "update", "delete", "query"] ) - """The OData filter expression to apply to this specific vector query. If no filter expression is - defined at the vector level, the expression defined in the top level filter parameter is used - instead.""" + """Controls how many vectors can be matched from each document in a vector search query. Setting + it to 1 ensures at most one vector per document is matched, guaranteeing results come from + distinct documents. Setting it to 0 (unlimited) allows multiple relevant vectors from the same + document to be matched. Default is 0.""" kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """Type of query. Required. Known values are: \"vector\", \"text\", \"imageUrl\", and \"imageBinary\".""" @@ -1566,22 +1546,22 @@ class VectorizableImageBinaryQuery(VectorQuery, discriminator="imageBinary"): no filter expression is defined at the vector level, the expression defined in the top level filter parameter is used instead. :vartype filter_override: str - :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector - query. If no filter expression is defined at the vector level, the expression defined in the - top level filter parameter is used instead. + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. :vartype per_document_vector_limit: int :ivar base64_image: The base 64 encoded binary of an image to be vectorized to perform a vector - search query. + search query. Required. :vartype base64_image: str :ivar kind: The kind of vector query being performed. Required. Vector query where a base 64 encoded binary of an image that needs to be vectorized is provided. :vartype kind: str or ~azure.search.documents.models.IMAGE_BINARY """ - base64_image: Optional[str] = rest_field( - name="base64Image", visibility=["read", "create", "update", "delete", "query"] - ) - """The base 64 encoded binary of an image to be vectorized to perform a vector search query.""" + base64_image: str = rest_field(name="base64Image", visibility=["read", "create", "update", "delete", "query"]) + """The base 64 encoded binary of an image to be vectorized to perform a vector search query. + Required.""" kind: Literal[VectorQueryKind.IMAGE_BINARY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The kind of vector query being performed. Required. Vector query where a base 64 encoded binary of an image that needs to be vectorized is provided.""" @@ -1590,6 +1570,7 @@ class VectorizableImageBinaryQuery(VectorQuery, discriminator="imageBinary"): def __init__( self, *, + base64_image: str, k_nearest_neighbors: Optional[int] = None, fields: Optional[str] = None, exhaustive: Optional[bool] = None, @@ -1598,7 +1579,6 @@ def __init__( threshold: Optional["_models.VectorThreshold"] = None, filter_override: Optional[str] = None, per_document_vector_limit: Optional[int] = None, - base64_image: Optional[str] = None, ) -> None: ... @overload @@ -1645,19 +1625,20 @@ class VectorizableImageUrlQuery(VectorQuery, discriminator="imageUrl"): no filter expression is defined at the vector level, the expression defined in the top level filter parameter is used instead. :vartype filter_override: str - :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector - query. If no filter expression is defined at the vector level, the expression defined in the - top level filter parameter is used instead. + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. :vartype per_document_vector_limit: int - :ivar url: The URL of an image to be vectorized to perform a vector search query. + :ivar url: The URL of an image to be vectorized to perform a vector search query. Required. :vartype url: str :ivar kind: The kind of vector query being performed. Required. Vector query where an url that represents an image value that needs to be vectorized is provided. :vartype kind: str or ~azure.search.documents.models.IMAGE_URL """ - url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of an image to be vectorized to perform a vector search query.""" + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URL of an image to be vectorized to perform a vector search query. Required.""" kind: Literal[VectorQueryKind.IMAGE_URL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The kind of vector query being performed. Required. Vector query where an url that represents an image value that needs to be vectorized is provided.""" @@ -1666,6 +1647,7 @@ class VectorizableImageUrlQuery(VectorQuery, discriminator="imageUrl"): def __init__( self, *, + url: str, k_nearest_neighbors: Optional[int] = None, fields: Optional[str] = None, exhaustive: Optional[bool] = None, @@ -1674,7 +1656,6 @@ def __init__( threshold: Optional["_models.VectorThreshold"] = None, filter_override: Optional[str] = None, per_document_vector_limit: Optional[int] = None, - url: Optional[str] = None, ) -> None: ... @overload @@ -1721,9 +1702,10 @@ class VectorizableTextQuery(VectorQuery, discriminator="text"): no filter expression is defined at the vector level, the expression defined in the top level filter parameter is used instead. :vartype filter_override: str - :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector - query. If no filter expression is defined at the vector level, the expression defined in the - top level filter parameter is used instead. + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. :vartype per_document_vector_limit: int :ivar text: The text to be vectorized to perform a vector search query. Required. :vartype text: str @@ -1805,9 +1787,10 @@ class VectorizedQuery(VectorQuery, discriminator="vector"): no filter expression is defined at the vector level, the expression defined in the top level filter parameter is used instead. :vartype filter_override: str - :ivar per_document_vector_limit: The OData filter expression to apply to this specific vector - query. If no filter expression is defined at the vector level, the expression defined in the - top level filter parameter is used instead. + :ivar per_document_vector_limit: Controls how many vectors can be matched from each document in + a vector search query. Setting it to 1 ensures at most one vector per document is matched, + guaranteeing results come from distinct documents. Setting it to 0 (unlimited) allows multiple + relevant vectors from the same document to be matched. Default is 0. :vartype per_document_vector_limit: int :ivar vector: The vector representation of a search query. Required. :vartype vector: list[float]